这个简单的示例向您展示了如何获取或设置状态JCheckBox。设置状态JCheckBox.setSelected(boolean)的方法为和获取状态的方法为JCheckBox.isSelected()返回布尔值。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; public class CheckBoxState extends JFrame { public CheckBoxState() throws HeadlessException { initialize(); } private void initialize() { setSize(300, 300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); // 创建带有文本标签的复选框 JCheckBox checkBox = new JCheckBox("Check me!"); checkBox.setSelected(true); // 获取复选框选择状态 boolean selected = checkBox.isSelected(); if (selected) { System.out.println("Check box state is selected."); } else { System.out.println("Check box state is not selected."); } getContentPane().add(checkBox); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new CheckBoxState().setVisible(true); } }); } }