问题
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