获得JToggleButton的状态

时间:2011-09-23 05:13:52

标签: java swing listeners jtogglebutton

说我有一个

JToggleButton but = new JToggleButton("OK") ;

现在我点击时需要but状态。我的意思是我需要知道它是否被点击。

2 个答案:

答案 0 :(得分:50)

您还可以使用itemListener的itemStateChanged方法,如下所示:

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

并且您想了解jtb后期使用isSelected()方法的状态

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

答案 1 :(得分:14)

要响应点击,请将ActionListener添加到JToggleButton。要找到它的状态,就像JRadioButton一样,调用它的isSelected()方法。

例如,

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