Add change listener to Button model : ButtonModel « Swing « Java Tutorial






import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main extends JFrame {
  JButton b = new JButton("Test");
  ButtonModel model = b.getModel();

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        System.out.println("Armed: " + model.isArmed() + " Enabled: "
            + model.isEnabled() + " Pressed: " + model.isPressed());
      }
    });

    getContentPane().add(b, BorderLayout.CENTER);

    pack();
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}








14.6.ButtonModel
14.6.1.Add change listener to Button model
14.6.2.Model for a JButton: manage only the state of the button
14.6.3.A default button model