简体   繁体   English

Java-我无法让两个actionListeners正常工作

[英]Java - I can't get two actionListeners to work right

Here's the ActionListener portion of my code. 这是我代码的ActionListener部分。 Focus on the reset button. 专注于重置按钮。

public void actionPerformed( ActionEvent e) {
    int i;
    for (i = 0; i < 26; i++) {
        if (e.getSource() == a[i]) { 
            consultWord(i); 
        }
    }

    if (e.getSource() == reset) {
        Hangman gui = new Hangman();
        System.out.print("test");
        gui.go();
    }
}   

Obviously there is much more above it (as this is at the VERY end). 显然,它上面还有更多的内容(因为这是非常极端的)。 Button array 1 (top if statement) works perfectly. 按钮数组1(if语句顶部)可以完美工作。 Button 2 (bottom if statement) doesn't work at all. 按钮2(if语句下方)根本不起作用。 The test output text does not appear. 测试输出文本不会出现。 Here is where I declared the variables. 这是我声明变量的地方。 (They are available to all code). (它们可用于所有代码)。

JButton reset = new JButton("Reset");
private Button a[];

And if it means anything to you, here's the code for setting up the a[] buttons. 如果对您来说有任何意义,这是设置a []按钮的代码。

int i;
StringBuffer buffer;
a = new Button[26];
topPanel.setLayout( new GridLayout( 4,0, 10, 10) );
for (i = 0; i <26; i++) {
    buffer = new StringBuffer();
    buffer.append((char)(i+'a'));
    a[i] = new Button(buffer.toString());
    a[i].setSize(100,100);
    a[i].addActionListener( this );
    topPanel.add(a[i]);
}

Any ideas why my bottom button isn't doing squat? 有什么想法为什么我的底部按钮没有下蹲吗? I'll paste my whole code if need be. 如果需要,我将粘贴整个代码。

Maybe you simply forgot to add the ActionListener to your reset button? 也许您只是忘记了将ActionListener添加到您的reset按钮中? This is missing from your code above… 上面的代码中缺少此信息...


As a side note some suggestions to make your code cleaner: 附带说明一下一些使代码更整洁的建议:

  • The StringBuffer is not needed: Simply use String.valueOf((char)(i+'a')) 不需要StringBuffer :只需使用String.valueOf((char)(i+'a'))
  • I would not use the same ActionListener for all buttons you have, as this clutters your actionPerformed method. 我不会对所有按钮使用相同的ActionListener ,因为这会使您的actionPerformed方法混乱。 Anonymous inner classes can be useful here. 匿名内部类在这里可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM