Java Program using JCheckBox with ActionListener
In this program, You will learn how to implement JCheckBox with ActionListener in java.
JCheckBox cb1, cb2, cb3;
public void actionPerformed(ActionEvent e) {
//statement
}
Example: How to implement JCheckBox with ActionListener in java.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
class Test extends JFrame implements ActionListener {
JButton jb1;
JCheckBox cb1, cb2, cb3;
Test() {
cb1 = new JCheckBox("China");
cb1.setBounds(50, 30, 150, 30);
add(cb1);
cb2 = new JCheckBox("India");
cb2.setBounds(50, 60, 150, 30);
add(cb2);
cb3 = new JCheckBox("Aus");
cb3.setBounds(50, 90, 150, 30);
add(cb3);
jb1 = new JButton("Click");
jb1.setBounds(50, 200, 100, 30);
add(jb1);
jb1.addActionListener(this);
setLayout(null);
setSize(600, 500);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String country = "";
if (cb1.isSelected()) {
country = country + "China\n";
}
if (cb2.isSelected()) {
country = country + "India\n";
}
if (cb3.isSelected()) {
country = country + "Aus\n";
}
JOptionPane.showMessageDialog(this, country);
}
public static void main(String args[]) {
Test t = new Test();
}
}