Toggle action from a button

Asked

Viewed 670 times

1

I’ve been searching the internet and I haven’t found anything that can explain me how I do to switch the action of a button in Java...

Example:
I have a button that when I press it I want it to change the texts of 2 bars, and when I press it again I want it to change the texts again... And let him do it as I squeeze.
They understood?
Now how do I do it?

  • 1

    If the action is "swap the text of two Labels" then you are not alternating anything, the action is the same every time...

  • 1

    I think the ideal is to use the text of the buttons themselves to figure out if you have to switch from X to Y or vice versa... it’s in the swing that?

  • I think I misinterpreted your question, it’s not to trade one label with the other, but to trade both for independent values, right?

  • Exactly! : ) When I click on this button I want it to replace the Jlabel string with another... Got it? @mgibsonbr

  • @Dongabi Having a reference to your JLabel, you have access to methods getText and setText to access your text, all you need to do is create a ActionListener to use these methods (and to switch between two, if you really need two actions, the way to do it is in my answer below).

1 answer

1


Literally answering the question, if you have two actions A and B (represented by interface implementations ActionListener) and you want to switch between one and the other, you can create a third class, generic, which also implements ActionListener and to perform this alternation between actions. An example of implementation would be:

class Alterna implements ActionListener {
    private ActionListener a;
    private ActionListener b;
    private boolean primeira = true;

    public Alterna(ActionListener a, ActionListener b) {
        this.a = a;
        this.b = b;
    }

    pubilc void actionPerformed(ActionEvent e) {
        if ( primeira )
            a.actionPerformed(e);
        else
            b.actionPerformed(e);
        primeira = !primeira; // Inverte, pra da próxima vez executar a outra ação
    }
}

So just create your two actions, normally then create an instance of that class and assign that instance as the button listener:

meuBotao.addActionListener(new Alterna(a, b));

Note: if by "swap the texts of 2 Labels" you mean "pass the text of label 1 pro label 2 and vice versa", then you don’t need two actions - one is enough! But if you mean "pass the text of label 1 to X and 2 to Y, in the other click pass label 1 to Z and 2 to W", then this approach is a possible way to do.

(another would for example use a ActionListener only and implement the same logic in it)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.