Reputation: 3213
When I press a key in a userID box I want the text in the textbook to be erased when the first key is pressed.
I thought that the code below would do that but it is not erasing the text in the text field.
How to set the text to empty in my JTextField?
Code:
@Override
public void keyPressed(KeyEvent e) {
final Component source = e.getComponent();
final JFrame frame = (JFrame) SwingUtilities.getRoot(source);
if (source instanceof JTextField){
((JTextField) source).setText("");
source.repaint();
}
}
I should mention that my KeyListener is in a completely different class.
class myKeyListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
final Component source = e.getComponent();
final JFrame frame = (JFrame) SwingUtilities.getRoot(source);
JTextField tf = (JTextField)e.getSource();
tf.setText("");
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Upvotes: 1
Views: 480
Reputation: 2864
Try using e.getSource():
@Override
public void keyPressed(KeyEvent e) {
JTextField tf = (JTextField)e.getSource();
tf.setText("");
}
The above code leaves the typed character in the box. If you want to end up with no characters (although, I'm not sure why you would want to do this), then maybe you should put this code in keyReleased()?
Upvotes: 1
Reputation: 51515
It's much easier to select the text in the JTextField, so when the user types a character, the text disappears.
JTextField textField = new JTextField(10);
textField.setText("Type in something here");
textField.setSelectionStart(0);
textField.setSelectionEnd(textField.getText().length());
Upvotes: 1