当前位置导航:炫浪网>>网络学院>>编程开发>>JAVA教程>>Java进阶

Swing的新JFormattedTextField 组件

  虽然 JFormattedTextField 组件看起来与 JTextField 相似,但是它的行为与 JSpinner 完全不同。在最简单的情况下,您可以为电话号码提供一个类似“(###)###-####”的输入掩码,它不会接受任何不遵循那个格式的输入。在较为复杂的情况下,既有显示格式化器,也有输入格式化器。例如:编辑时,缺省日期格式化器允许根据光标的位置在可用的月或日之间滚动。

  当使用 JFormattedTextField 时,可接受的输入或者是由掩码明确指定,或者是由组件的一个值指定。在后一种情况下,组件用工厂(Factory)设计模式来查找指定值类的缺省格式化器。 DefaultFormatterFactory 组件提供预先安装的日期、数字、 java.text.Format 子类的格式化器以及其他一切包罗万象的格式化器。

  配置可接受的输入

  # 一个数字 ? 一个字母 A 一个字母或数字 * 任意字符 U 一个字母,小写字符映射到与它们等效的大写字符上 L 一个字母,大写字符映射到与它们等效的小写字符上 H 一个十六进制数字(A-F、a-f、0-9) ' 用来转义另外一个掩码字符

  屏蔽输入一般是通过使用 MaskFormatter 类的一个实例配置的。在 javax.swing.text 包中发现, MaskFormatter 通过使用一系列字符指定可接受的输入来工作。该系列 8 个字符中的每一个都代表输入中的一个字符,下面的列表指出了这一点:

  除了 MaskFormatter 之外,您还可以用来自 java.text 软件包的 DateFormat 和 NumberFormat 类指定输入格式。清单 1 显示了一些可能的格式。

  清单 1. 定义输入掩码

1 // Four-digit year, followed by month name and day of month,
2 // each separated by two dashes (--)
3 DateFormat format =
4   new SimpleDateFormat("yyyy--MMMM--dd");
5 DateFormatter df = new DateFormatter(format);
6 // US Social Security number
7 MaskFormatter mf1 =
8   new MaskFormatter("###-##-####");
9 // US telephone number
10 MaskFormatter mf2 =
11   new MaskFormatter("(###) ###-####");
12

  一旦您指定了输入格式,您随后就要将格式化器传入 JFormattedTextField 构造器中,如下所示:

  还有其它一些可配置的选项,它们取决于您使用的格式化器。例如:用 MaskFormatter ,您能用 setPlaceholderCharacter(char) 设置占位符字符。另外,对于日期域,如果您将域初始化为某个值使一个用户知道什么样的输入格式是可接受的,这样将会有所帮助。

  全部组合在一起

  创建屏蔽输入域的一切都已就绪。清单 2 通过把以前的代码片断组合在一起,为您提供了一个用于检验新性能的完整示例。图 1 展示了这个示例的显示。随便调整各个掩码来检验其他的掩码字符。

  图 1. 活动中的 JFormattedTextField

  清单 2. JFormattedTextField 示例

1 import java.awt.*;
2 import javax.swing.*;
3 import javax.swing.text.*;
4 import java.util.*;
5 import java.text.*;
6 public class FormattedSample {
7   public static void main (String args[]) throws ParseException {
8     JFrame f = new JFrame("JFormattedTextField Sample");
9     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10     Container content = f.getContentPane();
11     content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
12     // Four-digit year, followed by month name and day of month,
13     // each separated by two dashes (--)
14     DateFormat format =
15       new SimpleDateFormat("yyyy--MMMM--dd");
16     DateFormatter df = new DateFormatter(format);
17     JFormattedTextField ftf1 = new
18       JFormattedTextField(df);
19     ftf1.setValue(new Date());
20     content.add(ftf1);
21     // US Social Security number
22     MaskFormatter mf1 =
23       new MaskFormatter("###-##-####");
24     mf1.setPlaceholderCharacter('_');
25     JFormattedTextField ftf2 = new
26       JFormattedTextField(mf1);
27     content.add(ftf2);
28     // US telephone number
29     MaskFormatter mf2 =
30       new MaskFormatter("(###) ###-####");
31     JFormattedTextField ftf3 = new
32       JFormattedTextField(mf2);
33     content.add(ftf3);
34     f.setSize(300, 100);
35     f.show();
36   }
37 }
38

相关内容
赞助商链接