Search code examples
javaswingjtogglebutton

Java Swing Making On/Off Button


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?


Solution

  • 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.