JComboBox outputComboBox = new JComboBox();
添加项
outputComboBox.addItem("源文件夹");
outputComboBox.addItem("自定义文件夹");
插入项
outputComboBox.insertItemAt("其他", 1)
设置默认选中
outputComboBox.setSelectedIndex(1);
获取选中项的索引
outputComboBox.getSelectedIndex()
事件
常用事件
// 添加ActionEvent监听器(确认选择时触发)
outputComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox<String> source = (JComboBox<String>) e.getSource();
String selected = (String) source.getSelectedItem();
System.out.println("ActionEvent - 确认选择: " + selected);
// 可在此处添加确认选择后的业务逻辑(如提交表单)
}
});
监听选项选中和取消选中
// 添加ItemEvent监听器(选项变化时触发)
outputComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// 只处理"选中"状态(避免一次变化触发两次事件)
if (e.getStateChange() == ItemEvent.SELECTED) {
String selected = (String) e.getItem();
System.out.println("ItemEvent - 选中: " + selected);
// 可在此处添加选项变化后的业务逻辑
}
}
});
原文出处:/show_1GW1cuPzNdQW.html