[英]Trouble passing an array to another class
我一直在通过向我制作的一个程序中添加一个使GUI成为类的类来练习挥杆。 我目前无法将数组发送到Visual类。
我现在要完成的操作是让按钮上的actionlistener运行并将标签更改为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
以便您可以在其他类中使用相关数据。 像这样:
public String print(){
//your code
return Answers[rnd];
}
这样,您可以在actionPerformed(ActionEvent)
方法中访问它。 像这样:
public void actionPerformed(ActionEvent event) {;
label.setText(new EightBall().print());
}
PS Java约定是camelCase用于字段/局部变量( Answers
应该是answers
, Scan
应该是scan
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.