Get selected JCheckBox

Complete source code below will show you, how to get selected JCheckBox.

***************************************************************************
COMPLETE SOURCE CODE FOR : GetSelectedJCheckBox.java
***************************************************************************


import javax.swing.JFrame;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JOptionPane;

import java.awt.GridLayout;

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

public class GetSelectedJCheckBox implements ActionListener
{
//Create String that will be use to hold selected JCheckBox text
String selectedCheckBox="";

//Create check box using JCheckBox
JCheckBox checkBox1=new JCheckBox("Duck");
JCheckBox checkBox2=new JCheckBox("Chicken");
JCheckBox checkBox3=new JCheckBox("Cow");
JCheckBox checkBox4=new JCheckBox("Sheep");

//Create button using JButton with text ( Get selected JCheckBox )
JButton button=new JButton("Get selected JCheckBox");

//method actionPerformed that we override because we implement ActionListener
public void actionPerformed(ActionEvent event)
{
//Action for button
if(event.getSource()==button)
{
//Check first JCheckBox is selected or not
if(checkBox1.isSelected())
{
selectedCheckBox=selectedCheckBox+checkBox1.getText()+"\n";
}

//Check second JCheckBox is selected or not
if(checkBox2.isSelected())
{
selectedCheckBox=selectedCheckBox+checkBox2.getText()+"\n";
}

//Check third JCheckBox is selected or not
if(checkBox3.isSelected())
{
selectedCheckBox=selectedCheckBox+checkBox3.getText()+"\n";
}

//Check fourth JCheckBox is selected or not
if(checkBox4.isSelected())
{
selectedCheckBox=selectedCheckBox+checkBox4.getText()+"\n";
}

//Show message that tell you, what check box that you selected
JOptionPane.showMessageDialog(null,"Selected check box is : \n"+selectedCheckBox);

//Make selectedCheckBox string like initial with empty string
selectedCheckBox=new String("");
}
}

//Constructor
public GetSelectedJCheckBox()
{
//Create a window using JFrame with title ( Get selected JCheckBox )
JFrame frame=new JFrame("Get selected JCheckBox");

//Create layout that will be use by JFrame
GridLayout gl=new GridLayout(5,1);

//Add ActionListener to button
button.addActionListener(this);

//Set JFrame layout
frame.setLayout(gl);

//Add all created check box into JFrame
frame.add(checkBox1);
frame.add(checkBox2);
frame.add(checkBox3);
frame.add(checkBox4);

//Add created button into JFrame
frame.add(button);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350,200);
frame.setVisible(true);
}

//Main method
public static void main(String[]args)
{
GetSelectedJCheckBox gsjcb=new GetSelectedJCheckBox();
}
}


***************************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************************

RELAXING NATURE VIDEO