JSpinner:精確數值/日期/列表選擇的最佳夥伴
滑動條難以精確定位時,JSpinner 透過上下按鈕微調,支援三大模型:
| 模型 | 適用場景 | 構造範例 |
| SpinnerNumberModel | 數值範圍、步長 | `new SpinnerNumberModel(3.4, -1.1, 4.3, 0.1)` |
| SpinnerDateModel | 日期時間區間 | `new SpinnerDateModel(init, start, end, Calendar.HOUR)` |
| SpinnerListModel | 離散列表(字串、圖標) | `new SpinnerListModel(new String[]{"A","B","C"})` |
日期格式化:JSpinner.DateEditor
SpinnerDateModel model = new SpinnerDateModel();
JSpinner spinner = new JSpinner(model);
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, "公元yyyy年MM月dd日 HH時");
spinner.setEditor(editor);
JList:多選、佈局方向、選擇模式全掌握
JList<String> list = new JList<>(books);
list.setVisibleRowCount(3);
list.setSelectionInterval(2, 4); // 預選
list.setLayoutOrientation(JList.VERTICAL_WRAP); // 佈局
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 選擇模式
- 監聽器:`ListSelectionListener` → `valueChanged` 取得 `getSelectedValues()`。
- 三種佈局:`VERTICAL`、`VERTICAL_WRAP`、`HORIZONTAL_WRAP`。
JComboBox:單選、可編輯、下拉行數
JComboBox<String> combo = new JComboBox<>(new Vector<>(books));
combo.setEditable(true); // 允許輸入
combo.setMaximumRowCount(4); // 可見行數
combo.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED)
System.out.println(combo.getSelectedItem());
});
核心差異速查
| 特性 | JList | JComboBox |
| 選擇模式 | 單選/多選/區間選 | 僅單選 |
| 顯示形式 | 列表區域常駐 | 下拉彈出 |
| 可編輯 | 需搭配編輯器 | `setEditable(true)` 內建 |
| 資料模型 | ListModel | ComboBoxModel |
實戰建議
- 固定選項少、單選 → `JComboBox`。
- 選項多、需多選或自定佈局 → `JList` + `JScrollPane`。
- 需精確數值/日期輸入 → `JSpinner`。