Reputation: 17
What would be the most simple solution each time a user presses a certain button the bool value changes? The only thing in my button action listener would be a call to a certain method for example Method1(); Or would working with a int be a more viable solution?
Thanks.
Upvotes: 1
Views: 7863
Reputation: 94
I think this is exactly what your looking for!! Hope it helps.
private boolean booly;
private class WinkAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (!booly){
booly = true;
}else {
booly = false;
}
}
}
Upvotes: 1
Reputation: 168845
I would recommend using a JToggleButton or JCheckBox for this case. It would be more natural to the user and either component can store it's state without declaring any further booleans.
E.G.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ToggleButton {
public static void main(String[] args) {
final JLabel result = new JLabel("Hit the button!");
final JToggleButton switchButton = new JToggleButton("Switch");
switchButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
result.setText("" + switchButton.isSelected());
}
} );
JPanel p = new JPanel(new GridLayout(0,1));
p.add(switchButton);
p.add(result);
JOptionPane.showMessageDialog(null, p);
}
}
Upvotes: 1
Reputation: 6038
Have a flag variable on the fields in your class.
Example:
private boolean bottonFlag = false.
in your method do:
bottonFlag = bottonFlag == true ? false : true; // this is to switch between true and false
Upvotes: 1