Java 2 标准版(J2SE),版本 1.4 为可用的 GUI 元素调色板添加了 2 个新的 Swing 组件:JSpinner 和 JFormattedTextField。在 Merlin 的魔力专栏的第一篇我们就介绍了 JSpinner 组件;我们现在将要探讨 JFormattedTextField。
虽然 JFormattedTextField 组件看起来与 JTextField 相似,但是它的行为与 JSpinner 完全不同。在最简单的情况下,您可以为电话号码提供一个类似“(###)###-####”的输入掩码,它不会接受任何不遵循那个格式的输入。在较为复杂的情况下,既有显示格式化器,也有输入格式化器。例如:编辑时,缺省日期格式化器允许根据光标的位置在可用的月或日之间滚动。
当使用 JFormattedTextField 时,可接受的输入或者是由掩码明确指定,或者是由组件的一个值指定。在后一种情况下,组件用工厂(Factory)设计模式来查找指定值类的缺省格式化器。DefaultFormatterFactory 组件提供预先安装的日期、数字、java.text.Format 子类的格式化器以及其他一切包罗万象的格式化器。
让我们看看如何使用组件。
配置可接受的输入
屏蔽输入一般是通过使用 MaskFormatter 类的一个实例配置的。在 javax.swing.text 包中发现,MaskFormatter 通过使用一系列字符指定可接受的输入来工作。该系列 8 个字符中的每一个都代表输入中的一个字符,下面的列表指出了这一点:
除了 MaskFormatter 之外,您还可以用来自 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 构造器中,如下所示:
JFormattedTextField ftf1 = new JFormattedTextField(df);
还有其它一些可配置的选项,它们取决于您使用的格式化器。例如:用 MaskFormatter,您能用 setPlaceholderCharacter(char) 设置占位符字符。另外,对于日期域,如果您将域初始化为某个值使一个用户知道什么样的输入格式是可接受的,这样将会有所帮助。
全部组合在一起
创建屏蔽输入域的一切都已就绪。清单 2 通过把以前的代码片断组合在一起,为您提供了一个用于检验新性能的完整示例。图 1 展示了这个示例的显示。随便调整各个掩码来检验其他的掩码字符。
图 1. 活动中的 JFormattedTextField
清单 2. 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(); } }
本文地址:http://com.8s8s.com/it/it13469.htm