2010-09-28 58 views
1

我想在Java中創建簡單的GUI程序,我找不到適當的解決方案,錯誤不能引用在不同的方法中定義的內部類中的非最終變量。不能引用非最終變量

這是我的小代碼到目前爲止;

myPanel = new JPanel(); 

JButton myButton = new JButton("create buttons"); 
myButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     int val = Integer.parseInt(textfield.getText()); 
     for(int i = 0; i < val; i++) { 
      JButton button = new JButton(""); 
      button.setText(String.valueOf(i)); 
      button.addActionListener(new ActionListener() { 
       public void actionPerformed(ActionEvent e) { 
        clickButton(i); 
       } 
      }); 
      myPanel.add(button); 
      myPanel.revalidate(); 
     } 
    } 
}); 

也許我的方法是完全錯誤的。我想要做的是;我想創建一組按鈕,並說當用戶按下一個按鈕時,我想顯示一條消息,如「您按下了按鈕4」或「您按下了按鈕10」。

回答

1

爲了避免這個問題,您必須聲明myPanel作爲類的成員變量,或者使用引用類的成員的其他東西。

7

i必須是最終的,以便內部類訪問它。您可以通過將其複製到最終變量來解決此問題。

但我建議重構的for循環的內容到這樣一個單獨的方法:

for(int i = 0; i < val; i++) { 
    myPanel.add(makeButton(i)); 
    myPanel.revalidate(); 
} 

... 

private JButton makeButton(final int index) { 
    JButton button = new JButton(""); 
    button.setText(String.valueOf(index)); 
    button.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      clickButton(index); 
     } 
    }); 

    return button; 
} 
1

匿名類只能使用聲明爲final,讓他們保證不會改變局部變量。

相關問題