Java Swing How to - Get Default button model, check button states








Question

We would like to know how to get Default button model, check button states.

Answer

/*  w w  w . j a  v  a  2 s  .co m*/
import javax.swing.DefaultButtonModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public static void main(String[] args) {
    JButton button = new JButton("ok");
    button.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        DefaultButtonModel model = (DefaultButtonModel) button.getModel();
        if (model.isEnabled())
          System.out.println("Enabled: true");
        else
          System.out.println("Enabled: false");

        if (model.isArmed())
          System.out.println("Armed: true");
        else
          System.out.println("Armed: false");

        if (model.isPressed())
          System.out.println("Pressed: true");
        else
          System.out.println("Pressed: false");
      }
    });
    JOptionPane.showMessageDialog(null, button);
  }
}