Getting the state of JToggleButton

牧云@^-^@ 提交于 2019-12-17 16:26:07

问题


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.


回答1:


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");
}



回答2:


To respond to clicks, add an ActionListener to the JToggleButton. To find it's state, just like a JRadioButton, call it's isSelected() method.

For e.g.,

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JToggleButton;

public class ToggleTest {
   public static void main(String[] args) {
      JToggleButton toggleBtn = new JToggleButton("Toggle Me!");
      toggleBtn.addActionListener(new ActionListener() {

         public void actionPerformed(ActionEvent e) {
            JToggleButton tBtn = (JToggleButton)e.getSource();
            if (tBtn.isSelected()) {
               System.out.println("button selected");
            } else {
               System.out.println("button not selected");
            }
         }
      });

      JOptionPane.showMessageDialog(null, toggleBtn);
   }
}


来源:https://stackoverflow.com/questions/7524536/getting-the-state-of-jtogglebutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!