Java implements ActionListener problem

In connection with the previous problem , I now have a new problem. To avoid the inner class, my class now implements 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 call a listener on my buttons from A to Z? Because all he can listen to is the last button , which in this case is the Z button.

Thank.

+3
source share
4 answers

You can listen to events from all the buttons just fine. Your problem is that you seem to think you can manipulate class fields. In fact, you do not need a field letterButtonat all for what you are trying to do:

public void actionPerformed (ActionEvent action){
    ((JButton)action.getSource()).setEnabled(false);
}
+5

. .

:

if(action.getSource() instanceof JButton){
    ((JButton)action.getSource()).setEnabled(false);
}
+2

, . , letterButton - . for ( letterButton = new JButton(buttonText);).

ActionListener ( ) "z".

: ActionCommand , , .

+2

, , , , , - gui ActionListener. , ?

action.getSource() == letterButton

In fact, is this line even compiling? I would be surprised if this were the way you are trying to assign value to a method call that does not make sense.

it would be better

letterButton == action.getSource();

Do you see why?

edit: ignore shit above. not enough sleep or caffeine. Sigh....

In addition, I answered your previous question about how to use an anonymous inner class and should not worry about declaring the variables final.

0
source

Source: https://habr.com/ru/post/1788815/


All Articles