-1

I need a small code in java for the following scenario:

Button should get the selected checkboxes and executing the code for those checkboxes in my form.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
Raj
  • 51
  • 1
  • 2
  • 4
  • 2
    Please perform an attempt yourself. Pointers: [Swing tutorials](http://docs.oracle.com/javase/tutorial/uiswing/components/index.html), `JButton#setAction` or `JButton#addActionListener`, `JCheckbox#isSelected` – Robin Nov 12 '12 at 17:44
  • Also look here: http://stackoverflow.com/questions/1509682/how-to-check-the-status-of-checkbox-in-java-gui – WilliamShatner Nov 12 '12 at 17:44

1 Answers1

10

Here is an example I made for you:

enter image description here

enter image description here

import java.awt.BorderLayout;
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;
import javax.swing.SwingUtilities;

public class TestJCheckBox {

    private JFrame frame;
    private JCheckBox jcb;
    private JButton button;

    public TestJCheckBox() {
        initComponents();
    }

    private void initComponents() {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        jcb = new JCheckBox("JCheckBox1");

        button = new JButton("Is JCheckBox selected?");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                if (jcb.isSelected()) {
                    JOptionPane.showMessageDialog(frame, "JCheckBox is selected");
                } else {
                    JOptionPane.showMessageDialog(frame, "JCheckBox is NOT selected");

                }
            }
        });

        frame.add(jcb, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestJCheckBox();
            }
        });
    }
}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    ThanQ . I think this is appropriate to my problem. And Sorry guys, i dont even have a time to code the thing. Anyways i'm glad with your concern. – Raj Nov 12 '12 at 19:46
  • 1
    @Raj its a pleasure.. As a helpful tip dont post questions in a rush or without an SSCCE as they have the potential to be closed relatively quickly-like this one. Do try and do your own work before turning to Q&As, a quick google on the seperate topics involved wouldnt hurt either :). – David Kroukamp Nov 12 '12 at 19:53