問題描述
我正在嘗試創(chuàng)建一個 JLabels 數(shù)組,單擊時它們都應(yīng)該不可見.當試圖通過需要訪問用于聲明標簽的循環(huán)的迭代變量的內(nèi)部類來設(shè)置鼠標偵聽器時,就會出現(xiàn)問題.代碼不言自明:
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
而不是調(diào)用 label[i]
來克服這個問題內(nè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是從內(nè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
才能從內(nèi)部(和匿名)類訪問.
Your local variable must be final
to be accessed from the inner (and anonymous) class.
您可以將代碼更改為以下內(nèi)容:
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:
任何使用但未在內(nèi)部類中聲明的局部變量、形參或異常參數(shù)都必須聲明為final
.
Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared
final
.
任何使用但未在內(nèi)部類中聲明的局部變量必須明確分配 (§16) 在內(nèi)部類的主體之前.
Any local variable used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
<小時>
資源:
- JLS - 內(nèi)部類和封閉實例
這篇關(guān)于訪問java內(nèi)部類中的變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!