How to get value of selected JCheckBox in 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
- {
-
- String selectedCheckBox="";
-
-
- JCheckBox checkBox1=new JCheckBox("Duck");
- JCheckBox checkBox2=new JCheckBox("Chicken");
- JCheckBox checkBox3=new JCheckBox("Cow");
- JCheckBox checkBox4=new JCheckBox("Sheep");
-
-
- JButton button=new JButton("Get selected JCheckBox");
-
-
- public void actionPerformed(ActionEvent event)
- {
-
- if(event.getSource()==button)
- {
-
- if(checkBox1.isSelected())
- {
- selectedCheckBox=selectedCheckBox+checkBox1.getText()+"\n";
- }
-
-
- if(checkBox2.isSelected())
- {
- selectedCheckBox=selectedCheckBox+checkBox2.getText()+"\n";
- }
-
-
- if(checkBox3.isSelected())
- {
- selectedCheckBox=selectedCheckBox+checkBox3.getText()+"\n";
- }
-
-
- if(checkBox4.isSelected())
- {
- selectedCheckBox=selectedCheckBox+checkBox4.getText()+"\n";
- }
-
-
- JOptionPane.showMessageDialog(null,"Selected check box is : \n"+selectedCheckBox);
-
-
- selectedCheckBox=new String("");
- }
- }
-
-
- public GetSelectedJCheckBox()
- {
-
- JFrame frame=new JFrame("Get selected JCheckBox");
-
-
- GridLayout gl=new GridLayout(5,1);
-
-
- button.addActionListener(this);
-
-
- frame.setLayout(gl);
-
-
- frame.add(checkBox1);
- frame.add(checkBox2);
- frame.add(checkBox3);
- frame.add(checkBox4);
-
-
- frame.add(button);
-
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(350,200);
- frame.setVisible(true);
- }
-
-
- public static void main(String[]args)
- {
- GetSelectedJCheckBox gsjcb=new GetSelectedJCheckBox();
- }
- }
isSelected Function is not working in IDE IntelliJ
ReplyDelete