麻烦将数组传递给另一个类

时间:2018-02-21 16:48:36

标签: java arrays class

我一直在练习摇摆,通过添加一个类来为我制作的程序之一制作GUI。我目前无法将我的数组发送到Visual类。

我现在想要完成的是按钮上的actionlistener运行并将标签更改为EightBall类中数组的随机元素的输出。

我的问题在于我不知道如何通过我的数组和随机对象发送它。

如何将信息传递给actionPerformed方法,以便我可以从Answers方法访问rndprint

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();
}
    }

1 个答案:

答案 0 :(得分:0)

更改print()课程中的EightBall方法以返回String,以便您可以使用其他课程中的相关数据。像这样:

public String print(){
    //your code
    return Answers[rnd];
}

这样您就可以使用actionPerformed(ActionEvent)方法访问它。像这样:

public void actionPerformed(ActionEvent event) {;
    label.setText(new EightBall().print());
}

P.S。 java约定是camelCase用于字段/局部变量(Answers应该是answersScan应该是scan