Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java implements ActionListener Problem

Tags:

java

swing

In relation to my previous problem, I now have a new problem. In order to avoid the inner class, my class now implements an actionListener. My code is as follows:

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);
        }
    }

How can I effect the listener to my buttons A to Z? Because all it can listen to is the last button which in this case is button Z.

Thank you.

like image 546
newbie Avatar asked May 18 '26 16:05

newbie


1 Answers

You listener can listen to events from all buttons just fine. Your problem is that you seem to believe that you can only manipulate class fields. In fact, you don't need the letterButton field at all for what you're trying to do:

public void actionPerformed (ActionEvent action){
    ((JButton)action.getSource()).setEnabled(false);
}
like image 118
Michael Borgwardt Avatar answered May 21 '26 16:05

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!