Java Swing Making On/Off Button

berkc picture berkc · Feb 7, 2015 · Viewed 7.5k times · Source

I am trying to make an on/off button for my GUI project. I made a button, when I click on it, a message appears. I used ActionListener for that. When I click it again, I want that message to dissappear. I tried to use jToggleButton but I don't know how to use it. Can anyone help?

Answer

alterfox picture alterfox · Feb 7, 2015

Here's an example of using a JToggleButton:

JToggleButton toggleButton = new JToggleButton("Click Me");
ItemListener itemListener = new ItemListener() {
    public void itemStateChanged(ItemEvent itemEvent) {
        int state = itemEvent.getStateChange();
        if (state == ItemEvent.SELECTED) {
            System.out.println("Selected"); // show your message here
        } else {
            System.out.println("Deselected"); // remove your message
        }
    }
};
toggleButton.addItemListener(itemListener);

You can use JButton and ActionListener as you've already started, but keep track of the current state yourself.