jcombobox用法
时间: 2023-08-21 20:50:15 浏览: 93
combobox的使用方法
3星 · 编辑精心推荐
JComboBox是Java Swing库中的一个组件,它可以让用户从下拉菜单中选择一个选项。下面是JComboBox的基本用法:
1. 创建JComboBox对象:
```java
JComboBox comboBox = new JComboBox();
```
2. 添加选项:
```java
comboBox.addItem("Option 1");
comboBox.addItem("Option 2");
comboBox.addItem("Option 3");
```
3. 设置默认选项:
```java
comboBox.setSelectedIndex(0); // 默认选择第一项
```
4. 监听选择事件:
```java
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
String selectedOption = (String) comboBox.getSelectedItem();
// 处理选择事件
}
});
```
完整示例代码:
```java
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxDemo implements ActionListener {
JComboBox comboBox;
public ComboBoxDemo() {
JFrame frame = new JFrame("ComboBox Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
comboBox = new JComboBox();
comboBox.addItem("Option 1");
comboBox.addItem("Option 2");
comboBox.addItem("Option 3");
comboBox.setSelectedIndex(0);
comboBox.addActionListener(this);
frame.add(comboBox);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
String selectedOption = (String) comboBox.getSelectedItem();
System.out.println("Selected option: " + selectedOption);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ComboBoxDemo();
}
});
}
}
```
阅读全文