下面的範例展示了如何在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建立和使用核取方塊(tw511.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);
}
}
執行上面範例程式碼,得到以下結果: