0

How do I prevent entering '.' character in JFormattedTextField (or JTextField if that easier) ?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Paul Taylor
  • 13,411
  • 42
  • 184
  • 351
  • 1
    For a JTextField, you could use a DocumentFilter, and there are many examples of this on this site (some written by me). For a JFormattedTextField, write a formatter that doesn't allow '.'. Surely you've checked out the tutorials for this class, right? If so, what have you tried and how is it now working? – Hovercraft Full Of Eels Jul 04 '13 at 20:39
  • 2
    Don't use a KeyListener for this as this won't work with copy and paste as well as has other problems. An example of a DocumentFilter solution can be found [here](http://stackoverflow.com/a/11093360). – Hovercraft Full Of Eels Jul 04 '13 at 21:05
  • So which is the best solution DocumentFilter with JTextField, or Mask with JFormattedTextField - Im unclear how to code a DocumentFilter to do what I want. – Paul Taylor Jul 05 '13 at 06:35
  • either can work fine. For an example of a DocumentFilter, please see the link that I have provided in my link above. – Hovercraft Full Of Eels Jul 05 '13 at 12:27

1 Answers1

1

You can also write a simple listener:

addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { if(e.getKeyChar() == '.') { e.consume(); } } });


Edit:

As @HovercraftFullOfEels mentioned in the comments, you better use DocumentFilter, see this answer for a good explanation and refer for the tutorial.

Edit 2:
You can try to MaskFormatter:

MaskFormatter formatter = new MaskFormatter(/*Check out the link*/);
JFormattedTextField tf = new JFormattedTextField(formatter );
Community
  • 1
  • 1
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 1
    I did look at maskFormatter but i didn't really have a format mask so dismissed it, i just wanted to ignore one char, but found setInvalidCharacters() which should do – Paul Taylor Jul 04 '13 at 20:53
  • 1
    This is not a good answer -1. KeyListeners need to be avoided in such situation as has been discussed *many* times on this and other sites. For one this solution will not work with copy and paste, a basic text component functionality. I've already mentioned a much better solution in my initial comment, a DocumentFilter. – Hovercraft Full Of Eels Jul 04 '13 at 21:02
  • 1
    I've re-added your JFormattedTextField info as it too is valid. Thanks. – Hovercraft Full Of Eels Jul 04 '13 at 21:19