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