简体   繁体   English

按 Enter 键时,文本字段中的 KeyListener 未触发

[英]KeyListener in Textfield not firing when press enter

I'm trying to make a program that can converts fahrenheit to celcius in java.我正在尝试制作一个可以在java中将华氏温度转换为摄氏度的程序。 In program i have 2 Labels and 1 TextField for input.在程序中,我有 2 个标签和 1 个 TextField 用于输入。 I want to make convert temperature when user types the temperature and presses Enter .我想在用户输入温度并按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.当我按下Enter监听器时,根本不触发。

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.编辑:它与 ActionListener 一起使用,但我需要使用匿名类来完成。 Without anonymous class it fires with Enter .如果没有匿名类,它会用Enter触发。

Try e.getKeyCode() instead of e.getKeyChar(). 尝试使用e.getKeyCode()而不是e.getKeyChar()。 The constant KeyEvent.VK_ENTER is an int, not a char. 常量KeyEvent.VK_ENTER是一个int,而不是一个char。

In other words: 换一种说法:

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

instead of 代替

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

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. 答案较晚,但是我尝试使用问题中的代码,并且KeyPressed确实触发了,但是由于JLabel没有更新,因此您认为没有触发KeyEvent。

Just after 刚过

outcome = input.getText(); 

add

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

so the label will update itself. 因此标签会自动更新。

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. 按钮不需要KeyListener (大多数情况下不应使用它们),它们使用ActionListener来响应所有激活事件,包括Enter ,鼠标单击和键盘快捷键,这是一个更为简化的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) 您还可以将按钮设置为“默认”按钮,当未聚焦时可以激活该按钮(只要当前聚焦的组件不使用/使用Enter键)

See JRootPane#setDefaultButton and How to Use Root Panes for more details 有关更多详细信息,请参见JRootPane#setDefaultButton如何使用根窗格

First of all, you need to implement all the methods from KeyListener. 首先,您需要实现KeyListener中的所有方法。 You haven't implemented keyTyped and keyReleased. 您尚未实现keyTyped和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. 另一件事是您应该检查键码而不是键字符,因为“ Enter”字符不可见,因此最好检查键码是否等于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. 最后一件事是,当您按下Enter键时,您将更新结果String变量,但未在任何地方显示它,因此需要在结果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);


}

}

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输入 ASCII 码是 10 而 KeyEvent.VK_ENTER 返回 13 回车

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM