2

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.

    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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Richard Rhyan
  • 203
  • 1
  • 6
  • 17

2 Answers2

3

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. Probably that's Gentoo compiled IcedTea 7.2 weirdness.

Otherwise everything works just fine, can you try my code, and if it doesn't work then what is your Java version?

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
  • I made the change you have (put the "####" in the MaskFormatter and it works! I can't believe nothing I could find online mentioned just putting the formatting text right in there. Thanks much – Richard Rhyan Feb 18 '12 at 22:13
2

Easiest way would be add Document to the JFormattedTextField with Number formatter, or another way is with add DocumentListener, for example

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319