JButton,點擊彈出日期時間選擇對話框。Application 與 Applet 部署。public class DateChooserJButton extends JButton {
private DateChooser dateChooser; // 內部類,實作選擇面板
private String preLabel; // 按鈕文字前綴
private static final SimpleDateFormat DEFAULT_FMT =
new SimpleDateFormat("yyyy年MM月dd日HH時");
// 建構子、setDate/getDate、setText 覆寫...
private class DateChooser extends JPanel
implements ActionListener, ChangeListener {
// 年/月/時 JSpinner、日曆 JButton[6][7]、JDialog 容器
// 顏色常數、建構子、createYearAndMonthPanel()...
// flushWeekAndDay() 重繪日曆、事件處理...
}
}
void showDateChooser(Point position) {
Frame owner = (Frame) SwingUtilities.getWindowAncestor(this);
if (dialog == null || dialog.getOwner() != owner)
dialog = createDialog(owner);
dialog.setLocation(getAppropriateLocation(owner, position));
flushWeekAndDay(); // 同步當前日期至面板
dialog.setVisible(true);
}
// 防止對話框超出螢幕邊界
Point getAppropriateLocation(Frame owner, Point position) {
// 計算偏移量,確保完整顯示
}
flushWeekAndDay():根據 yearSpin/monthSpin 計算當月天數,填充 6x7 按鈕矩陣,高亮當前日期(橘色背景)。stateChanged():監聽 Spinner 變更,更新 Calendar 模型並重繪日曆。actionPerformed():點擊日期按鈕 → 更新模型 → 關閉對話框(由外部關閉邏輯觸發)。
public void setDate(Date date) {
super.setText(preLabel + DEFAULT_FMT.format(date));
}
public Date getDate() {
String s = getText().substring(preLabel.length());
return DEFAULT_FMT.parse(s); // 異常時回傳當前時間
}
// 簡單使用
DateChooserJButton btn = new DateChooserJButton();
panel.add(btn);
// 取得選擇日期
Date selected = btn.getDate();
// 自訂格式
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
DateChooserJButton btn2 = new DateChooserJButton(fmt, "2024-01-15 14:30");
| 優點 | 缺點/改進建議 |
|---|---|
| 單一檔案、零依賴、易整合 | 硬編碼顏色/字型常數,建議暴露 Setter 或採用 UIManager |
| JSpinner 數值選擇直觀,支援鍵盤輸入 | 無分鐘/秒選擇,若需完整時間建議擴充 |
| 模態對話框阻塞流程,邏輯簡單 | 模態對話框在 Swing 中可能導致 EDT 阻塞,長操作需注意 |
| 相容舊版 Java (1.4+) | 建議遷移至 Java 8+ java.time API (LocalDateTime, DateTimeFormatter) |
LocalDateTime + DateTimeFormatter 替代 Date/Calendar。JSpinner.DateEditor 或第三方庫 (如 LGoodDatePicker) 簡化實作。DateChooserJButton 是一個緊湊、實用的 Swing 日期時間選擇元件,展示了 JSpinner、JDialog、自定義渲染等核心 Swing 技術的綜合應用。雖屬早期風格,但其封裝思想與交互細節(高亮、定位、格式化)仍具參考價值,適合作為教學案例或輕量專案的直接整合基礎。