【问题标题】:How to pass an int value to JButton actionlistener?如何将 int 值传递给 JButton actionlistener?
【发布时间】:2017-10-09 08:46:51
【问题描述】:

我正在制作一个测验程序,它会询问用户简单的数学问题、接收答案、计算用户的分数等等......

我收到一个错误,因为我在 actionListener 中使用了一个变量(在本例中为 x):

for(x = 0;x < total;x++){
System.out.print((x+1)+". ");

questionLabel.setText(number1" + "+ number2);

answerButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){
            int returnedAns = Integer.parseInt(answerTextField.getText());

                if(returnedAns == answerToTheQuestion){
                    score++;
                    System.out.println("correct");
                    question[x].result = true;
                }else{
                    System.out.println("wrong");
                    question[x].result = false;
                }

                try{
                    Thread.sleep(500);
                }catch(Exception e){}
            }
        });
    }

当我运行我的代码时,它会突出显示 int x 并说“从内部 clas 引用的局部变量必须是最终的或有效的最终”。

请帮帮我,我真的不知道该怎么办。

我无法将其标记为最终版本,因为我需要能够更改它以使 for 循环正常工作...

【问题讨论】:

  • 制作变量final :)
  • 但问题是我需要改变它....它的循环变量

标签: java swing arguments jbutton actionlistener


【解决方案1】:

最好的方法是为此 ActionListener 实现定义一个额外的类。

public class NumberedActionListener implements ActionListener {

  private int number;

  public NumberedActionListener(int number) {
    this.number = number;
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    // ...
  }
}

然后你可以将一个 int 值传递给构造函数。

answerButton.addActionListener(new NumberedActionListener(x));

如果你喜欢干净的代码,这看起来也更好......

【讨论】:

    【解决方案2】:

    您可以将x 的值分配给for 循环内的另一个变量,然后将该变量设为final。

    for(x = 0;x < total;x++){
       final int index = x;
       // use index inside your actionListener
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2012-02-23
      • 2020-07-24
      • 2020-06-16
      • 1970-01-01
      相关资源
      最近更新 更多