我有一些java代码,我得到了我的程序工作,但我想添加一些快捷键。出于某种原因,我不能让这个工作。它的代码与程序上的按钮相同,当我按下按钮时,它工作,但当我试着按回车键时,它不工作。有什么建议吗?
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();
}
}
}
看起来您正在尝试将KeyListener添加到JTextField并尝试捕获Enter键。如果是的话,不要这样做。相反,只需给JTextField一个ActionListener,它会做同样的事情,但实际上会工作。
。
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();
}
});