我有一些Java代码,程序正常运行,但我想添加一些关键的快捷方式。由于某种原因,我无法使它正常工作。它与程序上的按钮具有相同的代码,当我按下该按钮时,它起作用了,但是当我尝试按下Enter键时,它就不起作用了。有什么建议么?
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();
}
});