問題描述
我正在嘗試創建一個 JLabels 數組,單擊時它們都應該不可見.當試圖通過需要訪問用于聲明標簽的循環的迭代變量的內部類來設置鼠標偵聽器時,就會出現問題.代碼不言自明:
I'm trying to create an array of JLabels, all of them should go invisible when clicked. The problem comes when trying to set up the mouse listener through an inner class that needs access to the iteration variable of the loop used to declare the labels. Code is self-explanatory:
for(int i=1; i<label.length; i++) {
label[i] = new JLabel("label " + i);
label[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
label[i].setVisible(false); // compilation error here
}
});
cpane.add(label[i]);
}
我認為我可以通過使用 this
或者 super
而不是調用 label[i]
來克服這個問題內部方法,但我一直無法弄清楚.
I thought that I could overcome this by the use of this
or maybe super
instead of the call of label[i]
within the inner method but I haven't been able to figure it out.
編譯錯誤是:局部變量i是從內部類中訪問的;需要聲明為final`
The compilation error is: local variable i is accessed from within inner class; needs to be declared final`
我確定答案一定是我沒有想到的非常愚蠢的事情,或者我犯了一些小錯誤.
I'm sure that the answer must be something really silly I haven't thought of or maybe I'm making some small mistake.
任何幫助將不勝感激
推薦答案
您的局部變量必須是 final
才能從內部(和匿名)類訪問.
Your local variable must be final
to be accessed from the inner (and anonymous) class.
您可以將代碼更改為以下內容:
You can change your code for something like this :
for (int i = 1; i < label.length; i++) {
final JLabel currentLabel =new JLabel("label " + i);
currentLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
currentLabel.setVisible(false); // No more compilation error here
}
});
label[i] = currentLabel;
}
來自 JLS:
任何使用但未在內部類中聲明的局部變量、形參或異常參數都必須聲明為final
.
Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared
final
.
任何使用但未在內部類中聲明的局部變量必須明確分配 (§16) 在內部類的主體之前.
Any local variable used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
<小時>
資源:
- JLS - 內部類和封閉實例
這篇關于訪問java內部類中的變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!