单击波动中的按钮获取复选框值

时间:2012-11-12 17:37:34

标签: java swing jbutton jcheckbox

我需要在java中使用一个小代码来实现以下场景:

  

按钮应获取所选复选框并执行代码   我表单中的复选框。

1 个答案:

答案 0 :(得分:9)

这是我为你做的一个例子:

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();
            }
        });
    }
}