Martin Plávek
Martin Plávek

Reputation: 335

ActionListener in java performs action on the second click

I am programming my first complex application in Java, Swing. When I have added ActionListener to my JButton.

ActionListener changeButton = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e){
        if(startButton.getText() == "Spustit") {
            startButton.setText("STOP");
        } else {
            startButton.setText("Spustit");
        }
    }
}

I am adding ActionListener to the button itself

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
    startButton.addActionListener(changeButton);
}

Can you tell me where I coded ActionListener badly?

Thanks to all!

Upvotes: 2

Views: 3147

Answers (2)

Kamelkent
Kamelkent

Reputation: 329

Why are you adding the actionlistener in actionPerformed? I think you should do something like this:

public static void main(String[] args) {
    final JButton startButton = new JButton("Spustit");
    ActionListener changeButton = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (startButton.getText() == "Spustit") {
                startButton.setText("STOP");
            } else {
                startButton.setText("Spustit");
            }
        }
    };
    startButton.addActionListener(changeButton);
    // Add it to your panel where you want int
}

Upvotes: 1

engineercoding
engineercoding

Reputation: 832

You have coded the ActionListener good enough to be working, at least, for the action listener itself. The problem is that you are adding the action listener after an event (your second sample), thus your action listener will get called the second time you will click it.

A solution is very simple:

JButton button = new JButton();
button.addActionListener( new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      //...
    }
 });

Now the action listener should activate on the first click if you directly add a new ActionListener to the button, not after an action is performed

Upvotes: 4

Related Questions