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

Merlin Swing 新組件:JFormattedTextField 輸入格式化完全指南

     編輯:Java 相關知識

JFormattedTextField 核心特性

J2SE 1.4 新增 JFormattedTextField 與 JSpinner。外觀類似 JTextField,但行為不同:可指定輸入掩碼(如電話號碼 (###) ###-####),拒絕不符格式輸入;複雜情況下支援顯示/編輯雙格式化器(如日期編輯時可按光標位置滾動月/日)。

配置可接受輸入

主要透過 MaskFormatter (javax.swing.text) 指定掩碼字符:

字符含義
#數字
?字母
A字母或數字
*任意字符
U字母,小寫轉大寫
L字母,大寫轉小寫
H十六進制數字 (A-F,a-f,0-9)
'轉義掩碼字符

亦可用 java.text.DateFormat/NumberFormat 指定格式。範例定義日期、社安號、電話掩碼:

DateFormat format = new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter df = new DateFormatter(format);
MaskFormatter mf1 = new MaskFormatter("###-##-####"); // SSN
MaskFormatter mf2 = new MaskFormatter("(###) ###-####"); // 電話
JFormattedTextField ftf1 = new JFormattedTextField(df);
ftf1.setValue(new Date()); // 初始值提示格式

MaskFormatter 可用 setPlaceholderCharacter('_') 設置佔位符。

完整範例

整合三種格式化欄位:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
import java.text.*;
public class FormattedSample {
  public static void main(String args[]) throws ParseException {
    JFrame f = new JFrame("JFormattedTextField Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
    // 日期
    DateFormat format = new SimpleDateFormat("yyyy--MMMM--dd");
    DateFormatter df = new DateFormatter(format);
    JFormattedTextField ftf1 = new JFormattedTextField(df);
    ftf1.setValue(new Date());
    content.add(ftf1);
    // 社安號
    MaskFormatter mf1 = new MaskFormatter("###-##-####");
    mf1.setPlaceholderCharacter('_');
    content.add(new JFormattedTextField(mf1));
    // 電話
    MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
    content.add(new JFormattedTextField(mf2));
    f.setSize(300, 100);
    f.show();
  }
}

JFormattedTextField 運行畫面

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved