Swing中的JFormattedTextField組件實(shí)例
雖然Swing的JFormattedTextField組件看起來(lái)與 JTextField 相似,但是它的行為與 JSpinner 完全不同。在最簡(jiǎn)單的情況下,您可以為電話號(hào)碼提供一個(gè)類似“(###)###-####”的輸入掩碼,它不會(huì)接受任何不遵循那個(gè)格式的輸入。在較為復(fù)雜的情況下,既有顯示格式化器,也有輸入格式化器。例如:編輯時(shí),缺省日期格式化器允許根據(jù)光標(biāo)的位置在可用的月或日之間滾動(dòng)。
當(dāng)使用Swing的JFormattedTextField組件時(shí),可接受的輸入或者是由掩碼明確指定,或者是由組件的一個(gè)值指定。在后一種情況下,組件用工廠(Factory)設(shè)計(jì)模式來(lái)查找指定值類的缺省格式化器。 DefaultFormatterFactory 組件提供預(yù)先安裝的日期、數(shù)字、 java.text.Format 子類的格式化器以及其他一切包羅萬(wàn)象的格式化器。
配置可接受的輸入
屏蔽輸入一般是通過(guò)使用 MaskFormatter 類的一個(gè)實(shí)例配置的。在 javax.swing.text 包中發(fā)現(xiàn), MaskFormatter 通過(guò)使用一系列字符指定可接受的輸入來(lái)工作。該系列 8 個(gè)字符中的每一個(gè)都代表輸入中的一個(gè)字符,下面的列表指出了這一點(diǎn):
除了 MaskFormatter 之外,您還可以用來(lái)自 java.text 軟件包的 DateFormat 和 NumberFormat 類指定輸入格式。清單 1 顯示了一些可能的格式。
清單 1. 定義輸入掩碼
- // Four-digit year, followed by month name and day of month,
- // each separated by two dashes (--)
- DateFormat format =
- new SimpleDateFormat("yyyy--MMMM--dd");
- DateFormatter df = new DateFormatter(format);
- // US Social Security number
- MaskFormatter mf1 =
- new MaskFormatter("###-##-####");
- // US telephone number
- MaskFormatter mf2 =
- new MaskFormatter("(###) ###-####");
一旦您指定了輸入格式,您隨后就要將格式化器傳入 JFormattedTextField 構(gòu)造器中,如下所示:
還有其它一些可配置的選項(xiàng),它們?nèi)Q于您使用的格式化器。例如:用 MaskFormatter ,您能用 setPlaceholderCharacter(char) 設(shè)置占位符字符。另外,對(duì)于日期域,如果您將域初始化為某個(gè)值使一個(gè)用戶知道什么樣的輸入格式是可接受的,這樣將會(huì)有所幫助。
全部組合在一起
創(chuàng)建屏蔽輸入域的一切都已就緒。清單 2 通過(guò)把以前的代碼片斷組合在一起,為您提供了一個(gè)用于檢驗(yàn)新性能的完整示例。圖 1 展示了這個(gè)示例的顯示。隨便調(diào)整各個(gè)掩碼來(lái)檢驗(yàn)其他的掩碼字符。
清單 2.Swing的JFormattedTextField組件示例
- 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));
- // Four-digit year, followed by month name and day of month,
- // each separated by two dashes (--)
- DateFormat format =
- new SimpleDateFormat("yyyy--MMMM--dd");
- DateFormatter df = new DateFormatter(format);
- JFormattedTextField ftf1 = new
- JFormattedTextField(df);
- ftf1.setValue(new Date());
- content.add(ftf1);
- // US Social Security number
- MaskFormatter mf1 =
- new MaskFormatter("###-##-####");
- mf1.setPlaceholderCharacter('_');
- JFormattedTextField ftf2 = new
- JFormattedTextField(mf1);
- content.add(ftf2);
- // US telephone number
- MaskFormatter mf2 =
- new MaskFormatter("(###) ###-####");
- JFormattedTextField ftf3 = new
- JFormattedTextField(mf2);
- content.add(ftf3);
- f.setSize(300, 100);
- f.show();
- }
- }
【編輯推薦】