Reputation: 384
I have some java code and I got my program working but I wanted to add some key shortcuts. 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();
}
}
}
Upvotes: 1
Views: 101
Reputation: 285430
It looks like you're trying to add a KeyListener to a JTextField and trying to capture the Enter key press. If so don't. Instead just give the JTextField an ActionListener which will do the same thing but will actually work.
e.g.,
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();
}
});
Upvotes: 3