Java实现ActionListener问题
关于我的工作,我现在有一个新问题。为了避免内部类,我的类现在实现了一个Java实现ActionListener问题,java,swing,Java,Swing,关于我的工作,我现在有一个新问题。为了避免内部类,我的类现在实现了一个actionListener。我的代码如下: public class MainGame extends JDialog implements ActionListener { public MainGame(JDialog owner) { super(owner, true); initComponents(); jPanel1.setLayout(new Grid
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);
}
}
public类MainGame扩展JDialog实现ActionListener{
公共主游戏(JDialog所有者){
超级(所有者,真实);
初始化组件();
setLayout(新的GridLayout(3,9,3,5));
对于(char-buttonChar='a';buttonChar您的操作侦听器正在侦听您的所有按钮。但是,您只检查最后一个按钮
相反,你可以这样做:
if(action.getSource() instanceof JButton){
((JButton)action.getSource()).setEnabled(false);
}
我认为使用匿名内部类或私有内部类要比现在尝试做的事情好得多——让gui类实现ActionListener。话虽如此,这句话不是倒过来的吗
action.getSource() == letterButton
事实上,这行代码是否编译过?如果它编译过,我会感到惊讶,因为您试图为一个毫无意义的方法调用赋值
最好是
letterButton == action.getSource();
你明白为什么吗
编辑:忽略上面的废话。睡眠不足或咖啡因不足。叹息
另外,我已经回复了您之前的帖子,关于使用匿名内部类的方法,并且不必担心将变量声明为final。您的侦听器可以很好地侦听来自所有按钮的事件。您的问题是,您似乎认为您只能操作类字段。事实上,您不需要lettbutton
字段中显示您正在尝试执行的操作:
public void actionPerformed (ActionEvent action){
((JButton)action.getSource()).setEnabled(false);
}
实际上,您所提供的内容中缺少很多代码。我怀疑letterButton
是您的类中的一个字段。因此,您在for循环中一遍又一遍地分配此字段(通过letterButton=new JButton(buttonext);
)
然后,ActionListener将与您的字段进行比较(这是最后一个按钮),因此仅使用按钮“z”触发
可能的解决方案:在按钮上使用actionCommand来确定按下了哪个按钮。@满是鳗鱼的气垫船你建议我做什么?@满是鳗鱼的气垫船为什么不编译该行?为什么你会说它是向后的?@满是鳗鱼的气垫船letterButton==action.getSource()为什么?thanks@Hovercraft满是鳗鱼,这不是一个赋值,这是一个等式检查。@Hovercraft。没问题,有时会发生。:@newbie使用lettbutton.setActionCommand(buttonText);在您的侦听器中,例如:((JButton)action.getSource()).setEnabled(false);System.out.println(action.getActionCommand());