简体   繁体   English

Key Listener无法正常工作?

[英]Key Listener not working?

I have some java code and I got my program working but I wanted to add some key shortcuts. 我有一些java代码,我的程序工作,但我想添加一些关键的快捷方式。 For some reason I cannot get this to work. 出于某种原因,我不能让这个工作。 It has the same code as a button on the program and when I hit the button it works , but when I try hitting the enter key it's not working . 它与程序上的按钮具有相同的代码,当我按下按钮时,它可以正常工作,但是当我尝试按下回车键时它不起作用。 Any suggestions? 有什么建议么?

public void keyTyped(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_ENTER){
        try{
        al.add(Integer.parseInt(txtGrade.getText()));
        txtGrade.setText("");
        txtGrade.requestFocus();
        numOfGrades++;
        lblGRecord.setText(numOfGrades + " Grades Recorded");
        }
        catch(Exception ex){
            JOptionPane.showMessageDialog(this, "Please enter a number");
            txtGrade.selectAll();
            txtGrade.requestFocus();
        }
    }
}

It looks like you're trying to add a KeyListener to a JTextField and trying to capture the Enter key press. 看起来您正在尝试将KeyListener添加到JTextField并尝试捕获Enter键按下。 If so don't. 如果是这样的话。 Instead just give the JTextField an ActionListener which will do the same thing but will actually work. 相反,只需给JTextField一个ActionListener,它将执行相同的操作但实际上会工作。

eg, 例如,

txtGrade.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e) {
    try{
        al.add(Integer.parseInt(txtGrade.getText()));
        txtGrade.setText("");
        numOfGrades++;
        lblGRecord.setText(numOfGrades + " Grades Recorded");
    } catch(Exception ex){
        JOptionPane.showMessageDialog(this, "Please enter a number");
        txtGrade.selectAll();
    }
    txtGrade.requestFocusInWindow();
  }
});

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

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