Get button state from ButtonModel in Java

Description

The following code shows how to get button state from ButtonModel.

Example


/*w ww.  jav  a  2s . co  m*/

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

import javax.swing.DefaultButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public static void main(String[] args) {
    final JButton ok = new JButton("ok");

    JCheckBox cb = new JCheckBox("Enabled", true);

    ok.setBounds(40, 30, 80, 25);
    ok.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        DefaultButtonModel model = (DefaultButtonModel) ok.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");
      }

    });

    cb.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {
        if (ok.isEnabled())
          ok.setEnabled(false);
        else
          ok.setEnabled(true);
      }
    });

    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.

Get button state from ButtonModel 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