Create a button model from DefaultButtonModel in Java

Description

The following code shows how to create a button model from DefaultButtonModel.

Example


    //from  ww  w .ja  va 2s  . c o  m


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

The code above generates the following result.

Create a button model from DefaultButtonModel in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer