编写一个Java程序:按钮组件实例,展示了单选按 钮、复选框及按钮的使用方法。其中,按钮组件对象 图6-16 单造 btn_ok注册了单击事件监听器 ActionListener,当单击 该按钮时,会执行 actionPerformed(ActionEvent e)方法响应事件。
时间: 2024-04-30 14:18:38 浏览: 19
以下是一个简单的Java程序,展示了单选按钮、复选框和按钮的使用方法:
```java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ButtonDemo extends JFrame implements ActionListener {
private JLabel label;
private JRadioButton radio1, radio2;
private JCheckBox checkBox;
private JButton button;
public ButtonDemo() {
super("Button Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
label = new JLabel("Select an option:");
panel.add(label);
radio1 = new JRadioButton("Option 1");
radio1.setSelected(true);
panel.add(radio1);
radio2 = new JRadioButton("Option 2");
panel.add(radio2);
checkBox = new JCheckBox("Check me");
panel.add(checkBox);
button = new JButton("OK");
button.addActionListener(this);
panel.add(button);
add(panel);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String message = "Option 1 is " + (radio1.isSelected() ? "selected" : "not selected") +
"\nOption 2 is " + (radio2.isSelected() ? "selected" : "not selected") +
"\nCheckbox is " + (checkBox.isSelected() ? "checked" : "unchecked");
label.setText(message);
}
}
public static void main(String[] args) {
new ButtonDemo();
}
}
```
这个程序创建了一个窗口,包含了一个标签、两个单选按钮、一个复选框和一个按钮。当按钮被单击时,会执行 `actionPerformed()` 方法,更新标签显示哪些选项被选中或勾选。