It's difficult to be 100% sure, but it would appear you have a scope issue. You key handler can't see your fields.
public void someMethod() {
JTextField tf1 = new JTextField(10);
JTextField tf2 = new JTextField(10);
KeyHandler handler = new KeyHandler();
tf1.addKeyListener(handler);
tf2.addKeyListener(handler);
}
public class KeyHandler extends KeyAdapter{
public void keyTyped(KeyEvent e){
// Error, tf1 is unknown...
if (e.getSource() == tf1) {...}
}
}
If you want to be able to compare which field you have, you have two options. Declare the fields as instance fields or identify the fields via their name
property.
Option 1
public class SomeClass extends ... {
private JTextField tf1;
private JTextField tf2;
public void someMethod() {
JTextField tf1 = new JTextField(10);
JTextField tf2 = new JTextField(10);
KeyHandler handler = new KeyHandler();
tf1.addKeyListener(handler);
tf2.addKeyListener(handler);
}
public class KeyHandler extends KeyAdapter{
public void keyTyped(KeyEvent e){
// tf1 is now within scope :D
if (e.getSource() == tf1) {...}
}
}
}
Option 2
public void someMethod() {
JTextField tf1 = new JTextField(10);
tf1.setName("tf1");
JTextField tf2 = new JTextField(10);
tf2.setName("tf2");
KeyHandler handler = new KeyHandler();
tf1.addKeyListener(handler);
tf2.addKeyListener(handler);
}
public class KeyHandler extends KeyAdapter{
public void keyTyped(KeyEvent e){
Object source = e.getSource();
if (source instanceof JTextField) {
JTextField field = (JTextField)source;
String name = field.getName();
if ("tf1".equals(name)) {
// Hello TextField #1
}
}
}
}
Disclaimer
Now, I have no idea why you want to do what you want to do, but KeyListener
s are not the most suitable option for filtering or monitoring changes to text fields. For one, you have no guarantee in what order your listener will be called in, the fields Document
may or may not be updated before the listener is fired. Secondly, they are not fired if the user pastes text into the field.
A better choice would be to use a DocumentListener
, which can be used to monitor changes to the fields Document
or a DocumentFilter
, which can be used to filter content being sent to the document.