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?
Asked
Active
Viewed 8,660 times
2

berkc
- 525
- 3
- 9
- 21
-
1Could you show us what you've tried so far? – DennisW Feb 07 '15 at 13:03
-
I'm voting to close this question as off-topic because a matter well described in [How to Use Buttons, Check Boxes, and Radio Buttons](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html). – Andrew Thompson Feb 07 '15 at 13:13
1 Answers
5
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.

alterfox
- 1,675
- 3
- 22
- 37