2013-10-06 37 views
1
btnButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       try { 
        var1 = Float.parseFloat(txtBox.getText()); 
       } 
       catch(NumberFormatException n) { 
       } 
      } 
     }); 

我不能訪問到變量「VAR1」在這裏,我得到的錯誤:訪問變量的ActionEvent級

local variable var1 is accessed from within inner class; needs to be declared final

我如何可以訪問變量actionPerformed事件?聲明爲final不是有用的,因爲更改最終變量值是不可能的。

+0

1)'趕上(NumberFormatException的N) { }形式'趕上(例外五的'變化代碼){ ..'到'catch(Exception e){e.printStackTrace(); //非常翔實! ..'2)爲了更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

2

內部類ActionListener包含本地變量的副本。如果變量在本地類中發生變化,則內部類變量可能不同步。

我覺得更好,使其全球(場):

private float var1; 

... 

btnButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      try { 
       var1 = Float.parseFloat(txtBox.getText()); 
      } 
      catch(NumberFormatException n) { 
      } 
     } 
    }); 
+0

仔細重讀了這個問題和你的答案後,我意識到第一種方法是行不通的,因爲*「由於改變最終變量值是不可能的,所以聲明爲最終不是有用的。」*第二個策略應該起作用。 –

+0

對,我編輯了我的答案 –

+0

如果我把它作爲全局私有我得到:非靜態變量var1不能從靜態上下文引用 – binaryBigInt

2
var1 = Float.parseFloat(txtBox.getText());  

使該變量作爲member變量。

class outer { 
    //declare variable here 

btnButton.addActionListener(new ActionListener() 
    { 
    // assign here 

} 

// you can use it later 

JLS # chapter 8

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

Any local variable used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.

從規範這裏的一個例子:

+0

下如果你做出最終決定,你將無法分配它:-) OP將需要使它成爲一個成員,或定義一個可變包裝器。 – dasblinkenlight

+0

如果我讓var1最終我不能再訪問它(如第一篇文章中所寫)。如果我將它設爲私人,我會收到以下消息: 非法消息 – binaryBigInt

+0

@binaryBigInt如果將它們聲明爲成員變量,則無需使其成爲最終的。 –