下面的示例展示了如何在Java Swing应用程序中使用标准复选框。
使用以下API -
JCheckBox()
- 创建标准复选框。JCheckBox.setEnabled(false);
- 禁用复选框。JCheckBox.setMnemonic(KeyEvent.VK_C);
- 为键盘快捷键设置一个复选框。JCheckBox.setSelected(true);
- 设置选中的复选框。
示例
package com.yiibai.swingdemo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing创建和使用复选框(yiibai.com)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JCheckBox checkBox1 = new JCheckBox("Java/Swing");
JCheckBox checkBox2 = new JCheckBox("Python");
checkBox2.setEnabled(false);
JCheckBox checkBox3 = new JCheckBox("MySQL");
checkBox3.setMnemonic(KeyEvent.VK_C);
checkBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
JOptionPane.showMessageDialog(frame,
((JCheckBox)source).getText() + ": " + ((JCheckBox)source).isSelected());
}
});
panel.add(checkBox1);
panel.add(checkBox2);
panel.add(checkBox3);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
执行上面示例代码,得到以下结果: