Toggle action of a button

1

I've been researching the internet and found nothing that can explain me how I do to toggle the action of a button in Java ...

Example:
I have a button that when I tighten it I want it to change the texts of 2 labels, and when I press it again I want it to change the texts again ... And that it will do it as I squeeze. > Do you understand? Now how do I do this?

    
asked by anonymous 17.03.2015 / 18:44

1 answer

1
Answering the question literally, if you have two actions A and B (represented by implementations of the ActionListener interface) and you want to switch between one and the other, you can create a generic third class that also implements ActionListener and perform this alternation between actions. An example 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
    }
}

Then you just create your two actions, usually then create an instance of that class and assign this instance as a button listener:

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

Note: If you "change the text of 2 labels" you mean "pass the text from label 1 pro label 2 and vice versa", so you do not need two actions - one is enough! But if you meant to "pass the text from label 1 to X and from 2 to Y, on the other click from label 1 to Z and from 2 to W", then this approach is a possible way to do it. >

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

    
17.03.2015 / 20:52