1

I have code

    NumberFormat format = NumberFormat.getIntegerInstance();
    format.setGroupingUsed(false);

    JFormattedTextField jtf = new JFormattedTextField(format);

    jtf.setValue(new Integer(0));
    jtf.setColumns(10);

but when I input characters in text field they stay printed until i switch to another text field. I need to forbid characters input totally, i mean when character is inputted i need to delete at the moment or make somehow for character to not even appear for processing by listener if that is possible and also not to appear in text field ofcourse. I mean only characters which are digits must appear.

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
Vyacheslav
  • 3,134
  • 8
  • 28
  • 42

3 Answers3

0

I found a solution in possible duplicates for that question Restricting JTextField input to Integers

    NumberFormat format = NumberFormat.getIntegerInstance();
    format.setGroupingUsed(false);

    NumberFormatter numberFormatter = new NumberFormatter(format);
    numberFormatter.setValueClass(Long.class); 
    numberFormatter.setAllowsInvalid(false); //this is the key

    JFormattedTextField jFormattedTextField = new JFormattedTextField(numberFormatter);
Community
  • 1
  • 1
Vyacheslav
  • 3,134
  • 8
  • 28
  • 42
0

It has been some time since I have worked on Swing, but I think you can create your own Document and set it on the JTextField.

Then in the document object you can control which characters are accepted and rejected as the user types them in.

Here is an example setting a filter on a document:

Restricting JTextField input to Integers

Community
  • 1
  • 1
mjstam
  • 1,049
  • 1
  • 6
  • 5
0

I would use a JSpinner configured with a JSpinnerNumberModel. This is specifically designed for integer input, and also gives the benefit of up/down arrow buttons for changing with the mouse.

dsh
  • 12,037
  • 3
  • 33
  • 51