Java6学习笔记5——利用Swing开发复选框

import javax.swing.JFrame;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import java.awt.Container;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;

public class CheckDemo extends JFrame implements ItemListener {
JLabel label;
JCheckBox checkA;
JCheckBox checkB;
JCheckBox checkC;
JCheckBox checkD;
public static void main(String arg[]) {
new CheckDemo();
}
public CheckDemo() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
setLocation(250,150);
Container pane = getContentPane();
pane.setLayout(new BoxLayout(pane,BoxLayout.Y_AXIS));//从上到下纵向布置组件。

label = new JLabel("A,B,C,D");
pane.add(label);

checkA = new JCheckBox("Aardvark");
checkA.setSelected(true);//设置默认状态为选中
checkA.addItemListener(this);
pane.add(checkA);

checkB = new JCheckBox("Baracuda");
checkB.setSelected(true);
checkB.addItemListener(this);
pane.add(checkB);

checkC = new JCheckBox("Condor");
checkC.setSelected(true);
checkC.addItemListener(this);
pane.add(checkC);

checkD = new JCheckBox("Daryll");
checkD.setSelected(true);
checkD.addItemListener(this);
pane.add(checkD);

pack();
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
String text = "";
if(checkA.isSelected()) {
text += "A";
}
if(checkB.isSelected()) {
if(text.length() > 0)
text += ",";
text += "B";
}
if(checkC.isSelected()) {
if(text.length() > 0)
text += ",";
text += "C";
}
if(checkD.isSelected()) {
if(text.length() > 0)
text += ",";
text += "D";
}
if(text.length() > 0)
label.setText(text);
else
label.setText("-");
}
}

你可能感兴趣的:(java,C++,c,swing,C#)