【发布时间】:2018-02-21 16:48:35
【问题描述】:
我一直在通过向我制作的一个程序添加一个制作 GUI 的类来练习摇摆。我目前无法将我的数组发送到 Visual 类。
我现在想要完成的是让按钮上的动作监听器运行并将标签更改为EightBall 类中数组的随机元素的输出。
我的问题在于我不知道如何将我的数组和随机对象发送给它。
如何将信息传递给actionPerformed 方法,以便我可以从print 方法访问Answers 和rnd?
import java.util.Scanner;
import java.util.Random;
public class EightBall {
public void print() {
Scanner Scan = new Scanner(System.in);
System.out.print("What is your question?");
String question = Scan.next();
String [] Answers;
Answers = new String [8];
Answers[0] = "Unlikely";
Answers[1] = "Positive";
Answers[2] = "Yes";
Answers[3] = "No";
Answers[4] = "Ask Again Later";
Answers[5] = "Maybe";
Answers[6] = "ugh";
Answers[7] = "blag";
int rnd = new Random().nextInt(Answers.length); }
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing. *;
public class Visual extends EightBall implements ActionListener {
JTextField textField;
JButton button;
JLabel label;
public static void main(String[]args) {
Visual vis = new Visual();
vis.go();
}
public void go(){
EightBall ball = new EightBall();
label = new JLabel("Whate is you question?");
JFrame frame = new JFrame();
button = new JButton("Ask");
textField = new JTextField(20);
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(label);
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
frame.setTitle("Magic Eight Ball");
frame.setSize(1000,1000);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
EightBall eight = new EightBall();
eight.print();
label.setText();
}
}
【问题讨论】:
-
您需要在您的
EightBall.print()方法中返回一个String,然后您可以将其分配给JLabel.setText(String)方法