📅  最后修改于: 2020-09-28 04:52:10             🧑  作者: Mango
Checkbox类用于创建复选框。它用于打开(true)或关闭(false)选项。单击复选框将其状态从“打开”更改为“关闭”,或从“关闭”更改为“打开”。
public class Checkbox extends Component implements ItemSelectable, Accessible
import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
输出:
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
输出: