2

有人可以帮帮我吗...我已经尝试了各种方法(包括此处的帮助),但这不起作用。我正在使用带有 MaskFormatter 的 JFormattedTextField 将数据输入限制为 4(最大)位。

    static JFormattedTextField textPayout;

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

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

谢谢

4

2 回答 2

3

我刚刚尝试了这段代码,它在一个小问题上运行良好:

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 版本是什么?

于 2012-02-18T21:59:56.917 回答
2

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

于 2012-02-18T21:57:05.107 回答