KeyPressed Event

I am trying to learn something about the GUI using NetBeans6.8 starting from the GUI section in a java tutorial.

There is a simple exercise for the Celsius-Fahrenheit converter. I want me to have two TextFields: one for Celsius and one for Fahrenheit temperature; if the user enters the celsius text box, he gets the result "printed" in the text given in Fahrenheit. and vice versa.

So, I superimpose both text fields on one KeyTyped event, here is 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 + ""); 
}

This does not work. If I print something in a text box, I got this exception:java.lang.NumberFormatException: For input string: ""

Code that attaches 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 cannot modify it; it is auto-generated.]

+3
4

.getText() , , (.. , , ), parseInt NumberFormatException. KeyEvent, "7", 7 . , - "", . , keyUp.

catch try.

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
    }
}

, keydown, . - http://www.javacoffeebreak.com/java107/java107.html ( - NumberTextField)

+1

, , - celsiusText.addKeyListener, ?

, KEY_TYPED, , KEY_DOWN KEY_UP. KEY_DOWN , , . .

- try/catch, .

+1

, , keyDown, , , , , "".

0

-

This is a really old example. A better approach is to use a DocumentListener rather than a KeyListener.

0
source

Source: https://habr.com/ru/post/1763071/


All Articles