关于我的previous problem,我现在遇到了一个新问题.为了避免内部类,我的类现在实现了一个actionListener.我的代码如下:
public class MainGame extends JDialog implements ActionListener {
public MainGame(JDialog owner) {
super(owner, true);
initComponents();
jPanel1.setLayout(new GridLayout(3, 9, 3, 5));
for (char buttonChar = 'a'; buttonChar <= 'z'; buttonChar++) {
String buttonText = String.valueOf(buttonChar);
letterButton = new JButton(buttonText);
letterButton.addActionListener(this);
jPanel1.add(letterButton);
}
newGame();
}
public void actionPerformed (ActionEvent action){
if (action.getSource() == letterButton) {
letterButton.setEnabled(false);
}
}
如何影响我的按钮A到Z的监听器?因为它可以收听的是最后一个按钮,在这种情况下是按钮Z.
谢谢.
解决方法:
你的听众可以很好地收听所有按钮的事件.你的问题是你似乎相信你只能操纵类字段.实际上,您根本不需要letterButton字段来执行您要执行的操作:
public void actionPerformed (ActionEvent action){
((JButton)action.getSource()).setEnabled(false);
}
标签:java,swing
来源: https://codeday.me/bug/20190723/1517033.html