首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Swing 微調控制器 JSpinner 與列表框 JList/JComboBox 實戰

     編輯:Java 相關知識

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());
});

核心差異速查

特性JListJComboBox
選擇模式單選/多選/區間選僅單選
顯示形式列表區域常駐下拉彈出
可編輯需搭配編輯器`setEditable(true)` 內建
資料模型ListModelComboBoxModel

實戰建議

  • 固定選項少、單選 → `JComboBox`。
  • 選項多、需多選或自定佈局 → `JList` + `JScrollPane`。
  • 需精確數值/日期輸入 → `JSpinner`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved