简体   繁体   English

Java-MaskFormatter

[英]Java - MaskFormatter

Can someone please help me out... I've tried all kinds of things (including help on here) and this just doesn't work. 有人可以帮帮我吗...我尝试了各种各样的事情(包括此处的帮助),但这根本行不通。 I'm using JFormattedTextField with a MaskFormatter to restrict data entry to 4 (max) digits. 我正在将JFormattedTextField与MaskFormatter一起使用,以将数据输入限制为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);

The problem is that it's not restricting characters nor length (also, the texts starts to overlap itself if a non-number is entered). 问题在于,它不限制字符也不限制长度(而且,如果输入了非数字,则文本开始重叠。) And I've tried a wide variety of mask-like operations. 而且我尝试了多种类似面具的操作。 Can somebody please tell me what I'm doing wrong? 有人可以告诉我我在做什么错吗?

Thanks 谢谢

I've just tried this code and it worked just fine with one minor issue: 我刚刚尝试了这段代码,但在一个小问题上也能正常工作:

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);
    }
}

The issue is that initially text field comes up filled with 4 spaces, so I had to delete them. 问题在于,最初的文本字段出现了4个空格,因此我不得不删除它们。 Probably that's Gentoo compiled IcedTea 7.2 weirdness. 可能是Gentoo编译了IcedTea 7.2怪异的东西。

Otherwise everything works just fine, can you try my code, and if it doesn't work then what is your Java version? 否则,一切都可以正常工作,您可以尝试我的代码吗,如果不起作用,那么您的Java版本是什么?

最简单的方法是使用Number formatterDocument添加到JFormattedTextField ,或者另一种方法是使用add DocumentListener例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM