![](/img/trans.png)
[英]Java - JButton text disappears if actionPerformed defined afterwards
[英]Changing JButton text in GridLayout on ActionPerformed
我试图更改单击时的JButton文本。 按钮位于GridLayout中的数组中。 我尝试使用.setText,但是NetBeans显示错误。
从内部类引用的局部变量必须是final或有效的final
将变量从private更改为final并没有帮助。 我是Java的新秀,如果有任何帮助,我将不胜感激。
package widok;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Gameplay extends JFrame {
private JButton[] button = new JButton[25];
public Gameplay() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(5, 5));
for (int i = 0; i < 25; i++) {
button[i] = new JButton(" ");
button[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
button[i].setText("X");
}
});
getContentPane().add(button[i]);
}
pack();
setVisible(true);
}
}
谢谢!
这里的问题是“ i”,它具有for循环的本地上下文,但是actionPerformed不在同一上下文中。 由于“ i”正在更改,因此无法将其定为最终值
您可以执行的操作会发出操作源,例如,可以从Actionaevent获取操作源
public void actionPerformed(ActionEvent ae) {
JButton btn = (JButton)ae.getSource();
btn.setText("X");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.