Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
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[]) {
        JFrame frame = new JFrame("Selecting CheckBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JCheckBox checkBox = new JCheckBox("A");

        // Define ChangeListener
        ChangeListener changeListener = new ChangeListener() {
            public void stateChanged(ChangeEvent changeEvent) {
                AbstractButton abstractButton = (AbstractButton) changeEvent.getSource();
                ButtonModel buttonModel = abstractButton.getModel();
                boolean armed = buttonModel.isArmed();
                boolean pressed = buttonModel.isPressed();
                boolean selected = buttonModel.isSelected();
                System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
            }
        };
        // Attach Listeners
        checkBox.addChangeListener(changeListener);
        checkBox.setMnemonic(KeyEvent.VK_S);
        frame.add(checkBox, BorderLayout.NORTH);
        frame.setSize(300, 100);
        frame.setVisible(true);
    }
}