Getting the state of JToggleButton

Dewsworld picture Dewsworld · Sep 23, 2011 · Viewed 51k times · Source

Say I have a

JToggleButton but = new JToggleButton("OK") ;

Now I need the state of but when it is clicked. I mean I need to know if it's clicked or not.

Answer

Harry Joy picture Harry Joy · Sep 23, 2011

You can also use the itemListener's itemStateChanged method like follow:

JToggleButton jtb = new JToggleButton("Press Me");
jtb.addItemListener(new ItemListener() {
   public void itemStateChanged(ItemEvent ev) {
      if(ev.getStateChange()==ItemEvent.SELECTED){
        System.out.println("button is selected");
      } else if(ev.getStateChange()==ItemEvent.DESELECTED){
        System.out.println("button is not selected");
      }
   }
});

and of you want to know the state of jtb latter on use isSelected() method

System.out.println(jtb.isSelected());
if(jtb.isSelected()){
    System.out.println("button is selected");
} else {
    System.out.println("button is not selected");
}