在 Java Swing 圖形介面開發中,JComboBox 是最常用的下拉選單元件。它允許使用者從預設清單中選擇單一項目,也可設為可編輯模式讓使用者自行輸入。本文將透過完整範例,示範如何建立下拉選單、新增選項、處理選項變更事件,並搭配圖片切換功能。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxDemo extends JApplet implements ItemListener {
JLabel imageLabel;
ImageIcon icon1, icon2, icon3;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// 建立下拉選單並新增選項
JComboBox comboBox = new JComboBox<>();
comboBox.addItem("6");
comboBox.addItem("7");
comboBox.addItem("8");
comboBox.addItemListener(this); // 註冊事件監聽
contentPane.add(comboBox);
// 初始顯示預設圖片
imageLabel = new JLabel(new ImageIcon("images/6.gif"));
contentPane.add(imageLabel);
}
// 處理選項變更事件
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String selected = (String) e.getItem();
// 根據選項切換圖片
imageLabel.setIcon(new ImageIcon("images/" + selected + ".gif"));
}
}
}
comboBox.addItemListener(this) 將事件導向本類別ListCellRendererDefaultComboBoxModel 管理模型setEditable(true) 可允許使用者自行輸入文字getSelectedIndex() 取得索引值,getSelectedItem() 取得物件Q:圖片無法顯示怎麼辦?
A:確認圖片路徑正確,建議將圖片放在專案的 resources 目錄,使用 getClass().getResource() 載入,避免絕對路徑問題。
Q:如何在選單中顯示圖示?
A:實作 ListCellRenderer 介面,在 getListCellRendererComponent() 中回傳包含圖示的 JLabel。
掌握 JComboBox 基礎操作後,即可輕鬆建立互動式下拉選單,搭配事件處理實現動態介面更新,是 Swing 開發的必備技能。