6

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.

udondan
  • 57,263
  • 20
  • 190
  • 175
Miral
  • 403
  • 5
  • 13
  • 30
  • 2
    The event is been consumed higher up the event chain, hence it is never reaching you, better to use [Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) - Actually, it's better to use an `ActionListener` for what you are trying to do - that's what it's designed for - remember, [Enter] isn't always the "accept" key for every platform ;) – MadProgrammer Jan 13 '13 at 23:35
  • I was tried to use action listener. Everything went so good until i can't find how to check if enter key is pressed or not in ActionListener. – Miral Jan 13 '13 at 23:42
  • 2
    Does it matter? From a platform independent point of view, the `ActionListener` will be triggered when the user triggers the "accept" action for that platform. It just so happens that for most platforms, it's the [Enter] key. – MadProgrammer Jan 13 '13 at 23:44
  • In this case the program should run only if user presses enter key. I tried to use ActionListener but that leads me to KeyListener which listens to key actions. Am i wrong? – Miral Jan 13 '13 at 23:48
  • 1
    *"Am I wrong?"* Yes..and no. `KeyListener` is to low level an API for what you are trying to achieve. If you REALLY want to monitor for the [Enter] key, then you are going to have to replace the key binding begin used by the text field. This will, however, change the way that the application might work on other platforms, hence the reason for the `ActionListener`. This allows the look and feel to decide under what conditions the `ActionListener` is fired. Under most platforms, that's the [Enter] key... – MadProgrammer Jan 13 '13 at 23:50
  • 1
    Hmm.. I get your point. I will focus on ActionListener then. – Miral Jan 13 '13 at 23:53
  • Ok, i found an answer in this topic:[link](http://stackoverflow.com/questions/5525302/cannot-instantiate-type-actionlistener). Now it works perfectly. Thanks for the ideas. – Miral Jan 14 '13 at 02:19

5 Answers5

5

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();
}
Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
  • Nice suggestions, but, *"When i press enter listener don't fire at all"* the [Enter] key is being consumed higher up the event chain, meaning that the listener is never triggered - [Enter] is begin used by the text field for something else and is begin consumed – MadProgrammer Jan 13 '13 at 23:37
  • This is true, although I assume they are judging whether or not the listener fires, on whether or not the if statement actually causes an output to be printed. Perhaps I should not have made such an assumption... – Sinkingpoint Jan 13 '13 at 23:40
  • 1
    As I said, nice suggestion otherwise and one the OP should take into future consideration, just isn't going to help in this situation, sorry – MadProgrammer Jan 13 '13 at 23:42
1

First of all, you need to implement all the methods from KeyListener. You haven't implemented keyTyped and keyReleased. Another thing is you should check the key code instead of the key char because the "Enter" char is not visible, so preferably you should check if the key code equals KeyEvent.VK_ENTER. The last thing is when you hit enter you update the outcome String variable but you doesn't show it anywhere, so you need to set the text on the result JLabel. You also forgot to make the conversion. My explanation could be confusing but below is the code:

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

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(){

                @Override
                public void keyPressed(KeyEvent e){

                    if(e.getKeyCode() == KeyEvent.VK_ENTER){
                        outcome = input.getText();
                        double celsius = (((Double.valueOf(outcome)) - 32) * 5 / 9 );
                        result.setText("Temperature in Celcius is: " + celsius);
                    }       
                }

                @Override
                public void keyTyped(KeyEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void keyReleased(KeyEvent e) {
                    // TODO Auto-generated method stub

                }
            }
        );
}

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);


}

}
Jesus Flores
  • 640
  • 8
  • 15
0

Late answer, but I tried with the code in the question and the KeyPressed did trigger, but the because the JLabel didn't update, you assumed the KeyEvent wasn't fired.

Just after

outcome = input.getText(); 

add

result.setText("Temperature in Celcius is: " + outcome);

so the label will update itself.

0

Buttons don't need a KeyListener (and for the most part shouldn't use them), they use an ActionListener to respond to all activation events, including Enter, mouse clicks and keyboard shortcuts, it's a much more simplified API.

See How to Use Buttons, Check Boxes, and Radio Buttons, How to Write an Action Listeners and How to Use Actions for more details

You can also set a button as the "default" button which can be activated when not focused (so long as the currently focused component doesn't use/consume the Enter key)

See JRootPane#setDefaultButton and How to Use Root Panes for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

THIS SHOULD WORK

if (e.getKeyChar() == 10) {
    System.out.println("enter");
 }

Enter ASCII code is 10 while KeyEvent.VK_ENTER returns 13 for Carriage Return