Check Box With Event Listener in java Swing

CheckBox with EventListener in Java Swing

For CheckBox the more Common usage should be Combining is with event listener with the event listener, the checkBox can Act Different Action..


package JavaSwing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class CheckBoxWithEventListener
{
// Create Differnt CheBox
public static JCheckBox cbox1 = new JCheckBox("Name 1");
public static JCheckBox cbox2 = new JCheckBox("Name 2");
public static JCheckBox cbox3 = new JCheckBox("Name 3");
public static JCheckBox cbox4 = new JCheckBox("Name 4");

public static void main(String [] args)
{
//Create and set up a Frame window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("CheckBoxWithEventLisetner");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Define the panel to hold the CheckBox
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JLabel Message = new JLabel(" ",JLabel.CENTER);

//set up the Title for the panel
panel1.setBorder(BorderFactory.createTitledBorder("NAME"));
panel2.setBorder(BorderFactory.createTitledBorder("OUTPUT"));

//Add the CheckBox into the Panel
panel1.add(cbox1);
panel1.add(cbox2);
panel1.add(cbox3);
panel1.add(cbox4);

panel2.add(Message);

//Add Action Listenr

cbox1.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==1)
{
Message.setText("Name 1 is Selected");
}
else
{
Message.setText("Name 1 is Unselected");
}
}
});

cbox2.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==1)
{
Message.setText("Name 2 is Selected");
}
else
{
Message.setText("Name 2 is Unselected");
}
}
});

cbox3.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==1)
{
Message.setText("Name 3 is Selected");
}
else
{
Message.setText("Name 3 is Unselected");
}
}
});

cbox4.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==1)
{
Message.setText("Name 4 is Selected");
}
else
{
Message.setText("Name 4 is Unselected");
}
}
});

//Add the panel into the Frame
frame.setLayout(new GridLayout(2,1));
frame.add(panel1);
frame.add(panel2);

//set the Window to be Visible as the Default to be False

frame.pack();
frame.setVisible(true);
}
}
Image 1

Image 2


Image 3

Image 4

Comments

Popular posts from this blog

How to Create JTextField Validation in java swing.

Creating Chat Frame in Java Swing.