学习用最少的工作量达到格式化文本输入目的作者:John Zukowski 翻译:Sean2002.6.
利用输入验证和焦点监听接收格式化输入不会很困难。在这篇文章里,John向大家展示了如何用JFormattedTextField 组件提示输入数字,日期以及格式化的输入信息。
J2SE 1.4版本里面,加入了两个新的Swing组件:JSpinner和JFormattedTextField。我们在Merlin的魔术专栏的开始已经介绍了JSpinner组件,现在我们来了解一下JFormattedTextField。
尽管JFormattedTextField组件的外表跟JTextField看上去是一样的,但它们的行为却是完全不同。最简单的情况下,你可以给出一个电话号码的输入掩码"(###) ###-####",JFormattedTextField不会接受任何不符合这样格式的输入。复杂点的情况是有一个显示格式和一个输入格式。举个例子来说,默认的日期输入格式允许有效的月份或者日期编辑情况下在光标的位置滚动。
JFormattedTextField可以接收的输入一是被mask显式定义好了,二则是被组件的某一个值所指定了。基于后一种情况下,组件用了Factory设计模式来为这个指定的值找到默认的formatter。DefaultFormatterFactory组件产生提前内置了的日期格式,数字格式,java.text.Format的子类,以及任何包罗万象的格式化器。
下面让我们来看看如何让这个组件工作起来。
配置可接收的输入最经常地,我们用一个MaskFormatter实例来实现掩码输入。MaskFormatter类在javax.swing.text包中,用一系列字母来指定可输入的范围。这一系列八个字符每一个都代表了输入的一个字符,正如下面的列表:
# | 一个数字 |
? | 一个字母 |
A | 一个数字或者字母 |
* | 任何字符 |
U | 一个字母,小写字母被转换到相应的大写字母 |
L | 一个字母,大写字母被转换到相应的小子字母 |
H | 一个十六进制数字(A-F, a-f, 0-9) |
' | 转义字符 |
除了MaskFormatter以外,你也可以使用DateFormat和NumberFormat类来指定输入格式。下表显示了一些可能的格式。// 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 numberMaskFormatter mf1 = new MaskFormatter("###-##-####");// US telephone numberMaskFormatter mf2 = new MaskFormatter("(###) ###-####");一旦你确定了输入格式,就可以传递formatter到JFormattedTextField类的构造器,如下示例:JFormattedTextField ftf1 = new JFormattedTextField(df);除了依赖于所使用的formatter,还有其他一些配置可选。例如,使用了MaskFormatter,你可以用setPlaceholderCharacter(char)方法设置placeholder字符。同样,日期输入框的话,它可以为你输入框初始化一个值,使得用户知道输入的格式。总结所有一切只是创建一个掩码的输入框。下面程序为你给出了一个完全的例子,该例子通过结合前面的代码片断检验了这个新的格式化输入能力。下面的图片则显示了外观。任意调整formatter来检测一下其他输入掩码。代码: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(); }}