Java实现下拉式选择框中选中一个按钮,弹出第二个下拉式选择框
时间: 2024-01-25 18:41:17 浏览: 37
你可以使用 Java Swing 中的 JComboBox 类来实现下拉式选择框,并通过 addActionListener() 方法监听选择事件。当用户在第一个下拉式选择框中选择一个选项时,你可以在事件处理程序中添加代码来显示第二个下拉式选择框。
以下是一个简单的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboBoxExample extends JFrame implements ActionListener {
JComboBox<String> comboBox1, comboBox2;
public ComboBoxExample() {
// 创建第一个下拉式选择框
String[] items1 = {"选项1", "选项2", "选项3"};
comboBox1 = new JComboBox<>(items1);
comboBox1.addActionListener(this);
// 创建第二个下拉式选择框
String[] items2 = {"选项A", "选项B", "选项C"};
comboBox2 = new JComboBox<>(items2);
// 将组件添加到窗口中
setLayout(new FlowLayout());
add(comboBox1);
add(comboBox2);
// 设置窗口属性
setTitle("ComboBox Example");
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
// 当用户在第一个下拉式选择框中选择一个选项时,显示第二个下拉式选择框
if (e.getSource() == comboBox1) {
String selectedItem = (String) comboBox1.getSelectedItem();
if (selectedItem.equals("选项1")) {
comboBox2.setVisible(true);
} else {
comboBox2.setVisible(false);
}
}
}
public static void main(String[] args) {
ComboBoxExample example = new ComboBoxExample();
example.setVisible(true);
}
}
```
在上面的示例中,当用户在第一个下拉式选择框中选择“选项1”时,第二个下拉式选择框将显示出来。如果选择其他选项,则第二个下拉式选择框将隐藏。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)