java 三个单选按钮 选择第一个单选按钮 返回int型变量x值为1; 选择第二个单选按钮 返回int型变量值为2;选择第三个单选按钮 返回int型变量值为3
时间: 2023-05-30 18:03:04 浏览: 115
以下是实现这个功能的Java代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RadioButtonExample extends JFrame implements ActionListener {
JRadioButton button1, button2, button3;
JButton submitButton;
int x = 0;
RadioButtonExample() {
setTitle("Radio Button Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
button1 = new JRadioButton("Button 1");
button2 = new JRadioButton("Button 2");
button3 = new JRadioButton("Button 3");
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
group.add(button3);
submitButton = new JButton("Submit");
submitButton.addActionListener(this);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
radioPanel.add(button1);
radioPanel.add(button2);
radioPanel.add(button3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(submitButton);
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add(radioPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e) {
if (button1.isSelected()) {
x = 1;
} else if (button2.isSelected()) {
x = 2;
} else if (button3.isSelected()) {
x = 3;
}
JOptionPane.showMessageDialog(this, "You selected button " + x);
}
public static void main(String[] args) {
RadioButtonExample example = new RadioButtonExample();
example.setVisible(true);
}
}
```
这个程序创建了一个窗口,其中包含三个单选按钮和一个提交按钮。单选按钮使用ButtonGroup分组,以确保只有一个按钮可以被选中。当用户点击提交按钮时,程序检查哪个单选按钮被选中,并设置变量x的值。最后,程序显示一个对话框,告诉用户他们选择了哪个按钮。
阅读全文