2017-10-09 79 views
0

我正在做一個測驗程序,要求用戶簡單的數學問題,接受答案,計算用戶的分數等...如何將一個int值傳遞給JButton actionlistener?

我得到一個錯誤,因爲我使用的是一個變量情況下,X)一個ActionListener內:

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循環工作...

+1

使變量'final' :) – notyou

+0

但事情是我需要去改變它....它的循環變量 –

回答

1

可以的x值分配給另一個變量的for -loop和內然後讓這個變量最終。

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

最好的方法是爲此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)); 

這也看起來好多了,如果你喜歡乾淨的代碼...

相關問題