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)
If the action is "swap the text of two Labels" then you are not alternating anything, the action is the same every time...
– mgibsonbr
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?
– Gleison
I think I misinterpreted your question, it’s not to trade one label with the other, but to trade both for independent values, right?
– mgibsonbr
Exactly! : ) When I click on this button I want it to replace the Jlabel string with another... Got it? @mgibsonbr
– Dongabi
@Dongabi Having a reference to your
JLabel
, you have access to methodsgetText
andsetText
to access your text, all you need to do is create aActionListener
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).– mgibsonbr