【发布时间】:2012-11-13 02:12:49
【问题描述】:
我需要一个java中的小代码用于以下场景:
按钮应该获得选中的复选框并执行代码 我表单中的那些复选框。
【问题讨论】:
-
请自行尝试。指针:Swing tutorials、
JButton#setAction或JButton#addActionListener、JCheckbox#isSelected
标签: java swing jbutton jcheckbox
我需要一个java中的小代码用于以下场景:
按钮应该获得选中的复选框并执行代码 我表单中的那些复选框。
【问题讨论】:
JButton#setAction 或 JButton#addActionListener、JCheckbox#isSelected
标签: java swing jbutton jcheckbox
这是我为您制作的示例:
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();
}
});
}
}
【讨论】: