Search code examples
javauser-interfacekeypressnetbeans6.8

KeyPressed event


I'm trying to learn something about GUI, using NetBeans6.8, starting with the GUI section in The java tutorial.

There is a simple exercise for a Celsius-Fahrenheit converter. I want that to have two TextFields, one for Celsius and one for Fahrenheit temperature; if the user types in the celsius text field he got the result "printed" in the fahrenheit text filed. and vice versa.

So, i put on both the textfields one KeyTyped event, here's the code:

private void celsiusTextKeyTyped(java.awt.event.KeyEvent evt) {                                
    int cels = Integer.parseInt(celsiusText.getText());
    int fahr = (int)(cels * 1.8 + 32);
    fahrText.setText(fahr + ""); 
}                                    

private void fahrTextKeyTyped(java.awt.event.KeyEvent evt) {                                
    int fahr = Integer.parseInt(fahrText.getText());
    int cels = (int)(fahr / 1.8 - 32);
    celsiusText.setText(cels + ""); 
}

It doesn't work. If i type something in a textfield i got this exception: java.lang.NumberFormatException: For input string: ""

The code that attach the listeners:

celsiusText.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
        celsiusTextKeyTyped(evt);
    }
});

fahrText.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
        fahrTextKeyTyped(evt);
    }
});

[However, i can't modify it, it's autogenerated.]


Solution

  • Method .getText() returns a string not a number, if that string contains non-numeric characters (i.e. a letter, a space, nothing at all) then parseInt will throw a NumberFormatException. Since your using KeyEvent, as soon as you press say "7", the event is fired before 7 is entered into the text box. Thus the text box still only contains "", which is where the error comes from. You may wish to also listen to the keyUp event instead.

    You need to enclose your code in a try catch block.

    private void fahrTextKeyTyped(java.awt.event.KeyEvent evt)
    {   
        try
        {                             
            int fahr = Integer.parseInt(fahrText.getText());
            int cels = (int)(fahr / 1.8 - 32);
            celsiusText.setText(cels + "");
        }
        catch(NumberFormatException ex)
        {
            //Error handling code here, i.e. informative message to the user
        }
    }
    

    An alternative is you could filter out non-numbers on keydown event, see example here - http://www.javacoffeebreak.com/java107/java107.html (Creating a custom component - NumberTextField)