A default button model : ButtonModel « Swing « Java Tutorial






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

import javax.swing.ButtonModel;
import javax.swing.DefaultButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    final JButton ok = new JButton("ok");
    JCheckBox cb = new JCheckBox("Enabled", true);
    cb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (ok.isEnabled())
          ok.setEnabled(false);
        else
          ok.setEnabled(true);
      }
    });

    ButtonModel model = new DefaultButtonModel() {
      public void setEnabled(boolean b) {
        if (b)
          System.out.println("Pressed: true");
        else
          System.out.println("Pressed: false");

        super.setEnabled(b);
      }

      public void setArmed(boolean b) {
        if (b)
          System.out.println("Armed: true");
        else
          System.out.println("Armed: false");

        super.setArmed(b);
      }

      public void setPressed(boolean b) {
        if (b)
          System.out.println("Pressed: true");
        else
          System.out.println("Pressed: false");

        super.setPressed(b);
      }

    };

    ok.setModel(model);

    JFrame f = new JFrame();
    f.setLayout(new FlowLayout());
    f.add(ok);
    f.add(cb);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}








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