java jframe radio选择性别
时间: 2023-07-02 21:13:11 浏览: 105
您可以使用JRadioButton来实现性别的单选选择,以下是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
public class GenderSelection extends JFrame {
private JRadioButton maleRadioButton, femaleRadioButton, otherRadioButton;
private ButtonGroup genderButtonGroup;
public GenderSelection() {
setTitle("Gender Selection");
setLayout(new FlowLayout());
JLabel genderLabel = new JLabel("Select your gender:");
add(genderLabel);
maleRadioButton = new JRadioButton("Male");
femaleRadioButton = new JRadioButton("Female");
otherRadioButton = new JRadioButton("Others");
genderButtonGroup = new ButtonGroup();
genderButtonGroup.add(maleRadioButton);
genderButtonGroup.add(femaleRadioButton);
genderButtonGroup.add(otherRadioButton);
add(maleRadioButton);
add(femaleRadioButton);
add(otherRadioButton);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public String getSelectedGender() {
if (maleRadioButton.isSelected()) {
return "Male";
} else if (femaleRadioButton.isSelected()) {
return "Female";
} else {
return "Others";
}
}
public static void main(String[] args) {
GenderSelection genderSelection = new GenderSelection();
String selectedGender = genderSelection.getSelectedGender();
System.out.println("Selected gender: " + selectedGender);
}
}
```
您可以在main函数中创建GenderSelection对象,并通过调用getSelectedGender方法来获取用户选择的性别。
阅读全文