2012-01-26 97 views
3

我想我已經把自己編碼在這裏的一個角落了。我正在嘗試使用java swing來實現這個效果。Java swing - 點擊執行一個動作

單擊接下來的按鈕,從文件(通過行索引號)加載新行,然後如果文件行中的日期尚未到達,則灰化下一個按鈕。我的問題是,當我有以下代碼:

Scanner input = new Scanner(System.in); 
    System.out.println("Enter week number"); 
    int j = input.nextInt(); 
    String[] strArray = new String[4];   
    xmlLoader(j, strArray); 

    JButton nextButton = new JButton("Next"); 
    nextButton.setBounds(750, 250, 80, 30); 
    nextButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae){ 
      j++; 
      doNext(j, nextButton); 
     } 
    }); 

我無法通過第j,因爲它不是最終的,我不能在按鈕上改變什麼,如果它是最後的,helpppp!

具體錯誤:局部變量j從內部類中訪問;需要被宣佈爲最終

+0

'nextButton.setBounds(750,250,80,30);'不要這樣做。這是非常脆弱的。根據首選尺寸使用佈局和(如有必要)尺寸。 –

回答

7

您可以將j定義爲外部類中的字段。

class Sample{ 
    private int j; 

    void method() { 
    ... 
    nextButton.setBounds(750, 250, 80, 30); 
    nextButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae){ 
      j++; 
      doNext(j, nextButton); 
     } 
     }); 
    } 
} 
+2

+1秒前:-) – StanislavL

3

使j類字段,而不是聲明局部變量。

2

聲明你j變量爲:final Integer j = new Integer(0)。 您將能夠更改Integer類包裝的值。