I am making a simple GUI program in java. In this program I have made a simple jFrame where there is two separate textField, one for user input number(data type: double) and another for square of the input number as answer.

What I want is:

  • The event action to be KeyTyped(ie displaying square for every single number entered through keyboard).
    eg: entered number is 11 the answer should display 1 for first 1 ,
    and 121 after 2nd 1 is entered.

  • If wrong key is pressed eg a character 'g', then the wrong character 'g' is destroyed at the instance.

Hope I coud explain more clearly but if you get it, how can i do the same, any idea.

(Note: I am using Netbeans IDE 7.1)

Second part first:
You need to use the <Key_Event>.consume() method.
A complete code is as follows:

public void keyPressed(KeyEvent e){
  if(!(e.getKeyCode()>=48&&e.getKeyCode()<=57)&&e.getKeyCode()!=8)
  e.consume();
}

First part:
In the same keyPressed event,compute the square of the number currently in the TextField you are referring to and set it as the text for the result TextField.Whenever the user inputs a number,it is squared and displayed in the result field.

Butbe cautious:Whenever the value of result exceeds Double's limit,you will get negative numbers in the result Field.So whenever you encounter a number greater than say Math.sqrt(<max_double_value_possible>),then prompt the user in someway or create an Exception and handle it

KeyListener isn't designated for listening KeyEvents came from keyboard, for GUI based on Swing JComponents use KeyBinding instead

This article has been dead for over six months. Start a new discussion instead.