Java单选按钮监视器
时间: 2023-10-21 16:05:36 浏览: 79
Java中的单选按钮(JRadioButton)可以添加监视器(ActionListener),以便在用户选择按钮时执行某些操作。以下是一个简单的示例代码:
```
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class RadioButtonExample extends JFrame implements ActionListener {
private JRadioButton radioButton1, radioButton2, radioButton3;
public RadioButtonExample() {
super("Radio Button Example");
setLayout(new FlowLayout());
// 创建单选按钮并添加到窗口
radioButton1 = new JRadioButton("Option 1", true);
radioButton2 = new JRadioButton("Option 2");
radioButton3 = new JRadioButton("Option 3");
add(radioButton1);
add(radioButton2);
add(radioButton3);
// 创建按钮组并将单选按钮添加到组中
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
// 添加监视器
radioButton1.addActionListener(this);
radioButton2.addActionListener(this);
radioButton3.addActionListener(this);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == radioButton1) {
System.out.println("Option 1 selected");
} else if (e.getSource() == radioButton2) {
System.out.println("Option 2 selected");
} else if (e.getSource() == radioButton3) {
System.out.println("Option 3 selected");
}
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
```
在此示例中,我们创建三个单选按钮并将它们添加到窗口中。然后,我们创建一个按钮组并将单选按钮添加到组中。最后,我们为每个单选按钮添加一个监视器,并在用户选择某个选项时执行相应的操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)