I have a document listener that works just fine. However, I'd like to add some functionality to it so that when the user hits the Enter key, the focus shifts to another object. I can't figure out how to trap this. Here is my code:
txtNum1.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
setAnswer(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
setAnswer(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
setAnswer(e);
}
private void setAnswer(DocumentEvent e) {
if (txtNum1.getText().equals("")) {
num1 = 0;
} else {
num1 = Integer.parseInt(txtNum1.getText());
}
calcAnswer();
System.out.println(e); //trying to output the event 'Enter'
}
I can do this with a key listener, but I've been scolded on this site before about using that approach, so I'm trying to learn this the correct way.
Thanks!
EDIT: Per the suggestions below, I added the following code, but it seems to have no effect. Can anyone see what I am missing? Thanks!
/* If the user hits the Enter key, we want the focus to shift to
* the next text field */
txtNum1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtNum2.requestFocus();
}
});
On a JTextfield, you can trap the Enter
key simply by adding an ActionListener
. It will get fired when the users types enter