There is any way to automatically by default select text in JTextField
and JTextArea
when focusGained
event occurs?
Asked
Active
Viewed 419 times
1
-
You should look @mKorbel answer from here. http://stackoverflow.com/questions/10293135/jcombobox-focuslost-is-not-firing-why-is-that/10293343#10293343 – vels4j Nov 26 '12 at 04:56
3 Answers
6
You just said how to do it -- focusGained event of a FocusListener.
You can then get the JComponent whose focus has been gained via FocusEvent's getSource()
method and then call the selectAll()
method on it.
Something like:
FocusAdapter selectAllFocusAdapter = new FocusAdapter() {
public void focusGained(FocusEvent e) {
final JTextComponent tComponent = (JTextComponent) e.getSource();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tComponent.selectAll();
}
});
tComponent.selectAll();
}
};
myJTextField.addFocusListener(selectAllFocusAdapter);
otherJTextField.addFocusListener(selectAllFocusAdapter);
myTextArea.addFocusListener(selectAllFocusAdapter);

Hovercraft Full Of Eels
- 283,665
- 25
- 256
- 373
-
@mKorbel: thanks! Answer edited, and 1+ to your linked answer. – Hovercraft Full Of Eels Nov 25 '12 at 18:24
-
@Ricardo this answer to your question, notice, for JTextArea couldn't be selectAll the proper methods, I'd be moving with Caret to the end of text – mKorbel Nov 25 '12 at 19:37
6
This is what you need:
jTextField1.selectAll();
More below:
jTextField1.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if(jTextField1.getText().equals(initialText))
//jTextField1.setText("");
jTextField1.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
if(jTextField1.getText().equals(""))
jTextField1.setText("whatever");
}
});

Jatin
- 31,116
- 15
- 98
- 163
-
2+1 quite good :-) but common issue is about [Focus is asynchronous, required invokeLater in some cases](http://stackoverflow.com/a/10293343/714968) – mKorbel Nov 25 '12 at 18:23
5
Are you expecting something like
class MyFocusTextField extends JTextField {
{
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
FocusTextField.this.select(0, getText().length());
}
@Override
public void focusLost(FocusEvent e) {
FocusTextField.this.select(0, 0);
}
});
}
}

vels4j
- 11,208
- 5
- 38
- 63
-
2+1 quite good :-) but common issue is about [Focus is asynchronous, required invokeLater in some cases](http://stackoverflow.com/a/10293343/714968) – mKorbel Nov 25 '12 at 18:23
-