Add a FocusListener
to the field
When focusGained
is triggered, set the caret position of the field to the end of the text...
field.setCaretPosition(field.getDocument().getLength());
See How to write a focus listener for more details
Updated
To select all the text, you can use...
field.selectAll();
Which will move the cursor to the end.
What I've done in the past is create a utility class (AutoSelectOnFocusManager
for example), which has a single FocusListener
. Basically, you register (or unregister) JTextComponent
s with it and it manages the process for you. Saves a lot of repeated code :P
Updated with a simple example
Did this simple example to test the feedback in the comments, thought I'd just whack in as well...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Wackme {
public static void main(String[] args) {
new Wackme();
}
public Wackme() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field1 = new JTextField("Some text", 20);
JTextField field2 = new JTextField("Some text", 20);
field1.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
System.out.println("Move to end");
JTextField field = ((JTextField)e.getComponent());
field.selectAll();
//field.setCaretPosition(field.getDocument().getLength());
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field1);
frame.add(field2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}