問(wèn)題描述
我正在嘗試創(chuàng)建一個(gè) JLabels 數(shù)組,單擊時(shí)它們都應(yīng)該不可見(jiàn).當(dāng)試圖通過(guò)需要訪問(wèn)用于聲明標(biāo)簽的循環(huán)的迭代變量的內(nèi)部類(lèi)來(lái)設(shè)置鼠標(biāo)偵聽(tīng)器時(shí),就會(huì)出現(xiàn)問(wè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]);
}
我認(rèn)為我可以通過(guò)使用 this
或者 super
而不是調(diào)用 label[i]
來(lái)克服這個(gè)問(wèn)題內(nèi)部方法,但我一直無(wú)法弄清楚.
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.
編譯錯(cuò)誤是:局部變量i是從內(nèi)部類(lèi)中訪問(wèn)的;需要聲明為final`
The compilation error is: local variable i is accessed from within inner class; needs to be declared final`
我確定答案一定是我沒(méi)有想到的非常愚蠢的事情,或者我犯了一些小錯(cuò)誤.
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)部(和匿名)類(lèi)訪問(wèn).
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;
}
來(lái)自 JLS:
任何使用但未在內(nèi)部類(lè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)部類(lèi)中聲明的局部變量必須明確分配 (§16) 在內(nèi)部類(lèi)的主體之前.
Any local variable used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
<小時(shí)>
資源:
- JLS - 內(nèi)部類(lèi)和封閉實(shí)例
這篇關(guān)于訪問(wèn)java內(nèi)部類(lèi)中的變量的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!