Tar*_*han 1 java swing actionlistener
所以我有一个按钮,按下后,通过使用actionListener调用以下方法:
public Die[] roll(){
Die[] playerRoll = new Die[5];
//code goes in here...
return playerRoll;
}
Run Code Online (Sandbox Code Playgroud)
按下按钮后我想访问返回的playerRoll数组,但我不知道该怎么做.这是我试过的:
Die[] returnedArray = throwButton.addActionListener(new MyActionListener());
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误的说法 Type mismatch: Cannot convert from void to Die[]
我的整个代码工作包括actionListener中的代码,我只是想访问返回的变量.如果您需要其他代码,我将编辑此帖子.
编辑.我尝试尽可能少地粘贴代码,因为有很多代码所以我尝试粘贴相关的东西:
public class Dice {
static JButton throwButton = new JButton("Throw!");
static JButton scoreTitle = new JButton("Score!");
static JLabel playerRoll1 = new JLabel();
static JLabel playerRoll2 = new JLabel();
static JLabel playerRoll3 = new JLabel();
Die[] playerCurrentRoll;
boolean playerRolled = false;
static JButton throwButton = new JButton("Throw!");
frame.getContentPane().add(scoreTitle);
frame.getContentPane().add(playerRoll1);
frame.getContentPane().add(playerRoll2);
frame.getContentPane().add(playerRoll3);
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel jp = new JPanel();
frame.setContentPane(jp);
frame.getContentPane().add(throwButton);
throwButton.addActionListener(new MyActionListener());
frame.setVisible(true);
frame.setSize(400, 400);
}
public Die[] roll() {
Die[] playerRoll = new Die[5];
//A lot of code in here but it basically populates the playRoll array.
//This part of the code does work.
return playerRoll
}
public void scoreMethod() {
for (int i =0; i < playerCurrentRoll.length; i++) {
humanTotal += playerCurrentRoll[i].getValue();
humanScore.setText(Integer.toString(humanTotal));
}
}
Run Code Online (Sandbox Code Playgroud)
}
public class MyActionListener implements ActionListener {
Dice diceobj = new Dice();
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Dice.throwButton) {
// diceobj.roll();
diceobj.playerCurrentRoll = diceobj.roll();
System.out.println(diceobj.playerCurrentRoll);
diceobj.computerCurrentRoll = diceobj.roll();
}else if(e.getSource() == Dice.scoreTitle){
diceobj.scoreMethod();
System.out.println("Called the score method");
}
}
Run Code Online (Sandbox Code Playgroud)
}
似乎我没有粘贴我的代码.有些部分可能会丢失,但我可以保证一切正常.我知道这一点,因为当我按下Throw按钮时,它会给我输出数组(如system.out.println中的myactionlistener类所示).给我数组的内存地址.当我按下分数按钮并且它指向包含错误的行时它不起作用:
for (int i =0; i < playerCurrentRoll.length; i++) {
Run Code Online (Sandbox Code Playgroud)
位于scoreMethod(); 在骰子课上.
试试这个
Die[] returnedArray; // member variable
// Inside the container's constructor
throwButton.addActionListener(new MyActionListener());
public Die[] roll(){
Die[] playerRoll = new Die[5];
//code goes in here...
return playerRoll;
}
// Your custom ActionListener
class MyActionListener implements ActionListener {
@Override
public void onActionPerformed(ActionEvent e) {
returnedArray = roll();
}
}
Run Code Online (Sandbox Code Playgroud)