我有一些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();
}
}
}
答案 0 :(得分:3)
看起来您正在尝试将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();
}
});