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

JieFormattedDateBox:Swing 格式化日期時間輸入元件完整原始碼解析

     編輯:Java 相關知識

JieFormattedDateBox 是一個繼承 JFormattedTextField 並實作 SpinnerModel 的日期時間輸入元件,支援自訂格式、遮罩輸入、Spinner 整合、游標位置感知的增減邏輯。本文解析其核心設計與完整原始碼。

使用範例

// 日期時間完整格式
JieFormattedDateBox box = new JieFormattedDateBox("yyyy年MM月dd日HH點mm分ss秒");

// 僅時間
JieFormattedDateBox timeBox = new JieFormattedDateBox("HH:mm:ss");

// 整合 JSpinner
JSpinner spinner = new JSpinner();
JieFormattedDateBox fdb = new JieFormattedDateBox("yyyy-MM-dd");
spinner.setModel(fdb);
spinner.setEditor(fdb);

核心功能特性

  • 格式化顯示/編輯:內部使用 SimpleDateFormat 與 MaskFormatter 雙重保障。
  • 即時驗證:DocumentListener 監聽輸入變化,呼叫 checkTime() 解析並更新內部 Timestamp。
  • 焦點離開修正:FocusListener 在失去焦點時強制重置為合法值。
  • SpinnerModel 實作:getNextValue()/getPreviousValue() 根據游標位置決定增減單位(年/月/日/時/分/秒)。
  • 游標位置保持:setValue() 保留 caretPosition,提升編輯體驗。

關鍵演算法:游標感知增減

靜態陣列定義單位對應毫秒值:

static String[] alias = {"yyyy","MM","dd","HH","hh","mm","ss"};
static long[] times = {0, 0, 86400000, 3600000, 3600000, 60000, 1000};

testAlias(format, caret, index) 判斷游標落在哪個時間單位區間,getIncrease/Decrease 計算跨月/跨年邊界時的精確毫秒差值(含月份天數變化處理)。

完整原始碼結構

package org.jie.ui.formattedbox;

public class JieFormattedDateBox extends JFormattedTextField implements SpinnerModel {
    private String format;
    private SimpleDateFormat timeFormat;
    private Timestamp time;

    // 建構子:初始化格式、遮罩、DocumentListener、FocusListener
    public JieFormattedDateBox(String format) { ... }

    // 即時驗證邏輯
    void checkTime() { ... }

    // SpinnerModel 介面實作
    public Object getValue() { return getText(); }
    public void setValue(Object value) { ... }
    public Object getNextValue() { ... }
    public Object getPreviousValue() { ... }
    public void addChangeListener(ChangeListener l) {}
    public void removeChangeListener(ChangeListener l) {}

    // 靜態工具方法
    static boolean testAlias(String format, int caret, int index) { ... }
    static long getIncrease(int caret, String format, Timestamp time) { ... }
    static long getDecrease(int caret, String format, Timestamp time) { ... }
    public static String replace(String src, String replaceSrc, String replaceWith) { ... }
}

適用場景

  • 需嚴格格式控制的日期時間輸入表單。
  • 需鍵盤上下鍵逐級調整日期時間的介面。
  • 需整合 JSpinner 提供視覺化增減按鈕的場合。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved