You really want to check out this documentation: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Your code will look something like this:
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
KeyListener kl = MyCustomKeyListener();
firstName.addKeyListener(kl);
In your custom KeyListener
, override the keyTyped()
method to find the value of firstName
, look it up in the database to find the corresponding last name, then use it to set the value of lastName
.
This way you can make it so that every time a key is typed this will execute, or you can check and make sure only a specific key triggers action (like pressing return
).
Also, I should mention you can use an anonymous class for this. Instead of creating MyCustomKeyListener
, you can say:
firstName.addKeyListener(new KeyListener(){
void keyTyped(keyEvent e){
//whatever you want to happen when the key is typed in here
}
});
EDIT: As it has been pointed out, it may be better to use a DocumentListener
. This is done by accessing the underlying JTextField's document and adding the listener to that, as shown in the answer here: Value Change Listener to JTextField