关于swing:Java-MaskFormatter

Java - MaskFormatter

有人可以帮帮我吗...我已经尝试过各种方法(包括此处的帮助),但这是行不通的。
我正在将JFormattedTextField与MaskFormatter一起使用,以将数据输入限制为4(最大)个数字。

1
2
3
4
5
6
7
8
9
10
    static JFormattedTextField textPayout;

    MaskFormatter f;
try {
    f = new MaskFormatter("####");
} catch (ParseException e) {
    e.printStackTrace();
    return; // actual code not written yet.
}
textPayout = new JFormattedTextField(f);

问题在于,它不限制字符也不限制长度(而且,如果输入了非数字,则文本开始重叠。) 而且我尝试了多种类似面具的操作。 有人可以告诉我我在做什么错吗?

谢谢


我刚刚尝试了这段代码,但在一个小问题上也能正常工作:

1
2
3
4
5
6
7
8
9
10
11
12
class A extends JFrame {
    public static void main(String args[]) throws ParseException {
        A a = new A();
        a.setLayout(new GridLayout());
        JFormattedTextField textField =
                new JFormattedTextField(new MaskFormatter("####"));
        a.add(textField);
        a.add(new JButton("qwe"));
        a.setSize(300,50);
        a.setVisible(true);
    }
}

问题在于,最初的文本字段出现了4个空格,因此我不得不将其删除。 可能是Gentoo编译了IcedTea 7.2怪异的东西。

否则,一切都可以正常工作,您可以尝试我的代码吗?如果不起作用,那么您的Java版本是什么?


最简单的方法是使用Number formatter将Document添加到JFormattedTextField,或者另一种方法是使用Add DocumentListener,例如