Listen to JCheckBox Events with an ActionListener in Java
Description
The following code shows how to listen to JCheckBox Events with an ActionListener.
Example
//from w ww .j a v a 2s . c o m
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println(selected);
// abstractButton.setText(newLabel);
}
};
aCheckBox4.addActionListener(actionListener);
frame.add(aCheckBox4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »