简体   繁体   中英

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

Here's the ActionListener portion of my code. 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. Button 2 (bottom if statement) doesn't work at all. 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.

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? 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'))
  • I would not use the same ActionListener for all buttons you have, as this clutters your actionPerformed method. Anonymous inner classes can be useful here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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