Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyListener in Textfield not firing when press enter

I'm trying to make a program that can converts fahrenheit to celcius in java. In program i have 2 Labels and 1 TextField for input. I want to make convert temperature when user types the temperature and presses Enter. To do that, i added a key listener to my textfield but it doesn't work. When i press Enter listener don't fire at all.

And here's my code.

public class TempConv extends JFrame{

private JLabel info;
private JLabel result;
private JTextField input;
private String outcome;

public TempConv(){

    super("Temperature Converter");
    setLayout(new BorderLayout());

    info = new JLabel("Enter Fahrenheit Temperature");
    add(info, BorderLayout.NORTH);

    input = new JTextField(12);
    add(input, BorderLayout.CENTER);

    result  = new JLabel("Temperature in Celcius is: " + outcome);
    add(result, BorderLayout.SOUTH);

    input.addKeyListener(
            new KeyListener(){

                public void keyPressed(KeyEvent e){

                    if(e.getKeyChar() == KeyEvent.VK_ENTER){

                        outcome = input.getText();
                    }       
                }
            }
        );
}

public static void main(String[] args) {


    TempConv ftc = new TempConv();
    ftc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ftc.setLocationRelativeTo(null);
    ftc.setSize(370, 100);
    ftc.setVisible(true);


}

}

Edit: It works with ActionListener but i need to do it with anonymous class. Without anonymous class it fires with Enter.

like image 537
Miral Avatar asked Jan 13 '13 23:01

Miral


1 Answers

Try e.getKeyCode() instead of e.getKeyChar(). The constant KeyEvent.VK_ENTER is an int, not a char.

In other words:

if(e.getKeyCode() == KeyEvent.VK_ENTER){
      outcome = input.getText();
}

instead of

if(e.getKeyChar() == KeyEvent.VK_ENTER){
      outcome = input.getText();
}
like image 76
Sinkingpoint Avatar answered Oct 24 '22 19:10

Sinkingpoint