0

I am trying to retrieve the values from a JTextField on a keypress to do something if the values are integers and to clear the field if the values are not integers. Every time I try to retrieve the value, I am getting the value entered before that(if I enter 12 I get 1 back then if I enter 123 I get 12 back) and when I try to clear the field on an invalid character everything but the invalid character gets cleared?

public void setUpListeners()
{
    JTextField jT [] = myV.getTextFields();

    jT[0].addKeyListener(new KeyAdapter(){ 
        public void keyTyped(KeyEvent e){
            int id = e.getID();

            if (id == KeyEvent.KEY_TYPED) 
            {
                char c = e.getKeyChar();
                try
                {
                    //check if chars entered are numbers
                    int temp = Integer.parseInt(String.valueOf(c));
                    String tempS = jT[0].getText();
                    System.out.println(tempS);
                }
                catch(Exception ex)
                {
                    jT[0].setText("");
                    System.out.println("Not an integer");

                }
            }
        }
   });
 }
earandap
  • 1,446
  • 1
  • 13
  • 22
Rich
  • 15
  • 9
  • 2
    Don't use `KeyListener`, see [Restricting JTextField input to Integers](https://stackoverflow.com/q/11093326/1048330) for a better implementation using either a `DocumentFilter.` or a `JFormattedTextField`. – tenorsax Oct 25 '19 at 21:03
  • Don't use a text field. `new JSpinner(new SpinnerNumberModel(5,0,100,1));` is kinder to the end user. – Andrew Thompson Oct 26 '19 at 02:15

2 Answers2

0

You could do the following:

public static boolean validateNumber(char num){
    return (num >= '0' && num <='9');
}

And then use parameter KeyEvent "e":

if(!validateNumber(e.getKeyChar()))
    e.consume();

And instead of using

public void keyTyped(KeyEvent e){

use

public void keyReleased(KeyEvent e){

I think you will get what you need, I hope I have helped you ;)

Israel-ICM
  • 150
  • 3
  • 5
  • Thanks for the answer its working perfect for the invalid characters now but when I type in a valid number I am still having the issue of it lagging behind? – Rich Oct 25 '19 at 21:53
  • I am getting: java.lang.NumberFormatException: For input string: "" for my first character even when it is a number I'm not sure why. – Rich Oct 25 '19 at 22:34
  • The Exception you receive seems to me to be the value you entered as empty "" but with the keyreleased it should be fixed – Israel-ICM Oct 25 '19 at 23:32
  • Ahhh I see why that is now thank you very much for your response again! – Rich Oct 25 '19 at 23:39
0

Swing components use Model-View-Controller (MVC) [software] design pattern / architecture. The model holds the data. For a JTextField the data is the text it displays. The default model for JTextField is PlainDocument, however JTextField code actually refers to the Document interface which PlainDocument implements.

Look at the code for method getText() in class JTextComponent (which is the superclass for JTextField) and you will see that it retrieves the text from the Document.

When you type a key in JTextField, the character gets passed to the Document. It would appear that your keyTyped() method is invoked before the character you typed reaches the Document, hence when you call getText() in your keyTyped() method, you're getting all the text apart from the last character you typed.

That's one of the reasons not to use a KeyListener in order to validate the text entered into a JTextField. The correct way is detailed in the question that tenorsax provided a link to in his comment to your question.

Apart from DocumentFilter or JFormattedTextField (or even InputVerifier), you can add an ActionListener to JTextField which will execute when you hit Enter in the JTextField. You will find many on-line examples of how to implement each one of these options, including the link provided in tenorsax comment.

Abra
  • 19,142
  • 7
  • 29
  • 41