force JTextField to select all of its contents when it appears

Benjamin Albert picture Benjamin Albert · Jan 2, 2013 · Viewed 26.2k times · Source

I have a JLabel that when you click on it its replaced with a JTextField, I need that JTextField to automaticity select all of its text when it appears.

Thank allot for the help.

Answer

JayC667 picture JayC667 · Jan 2, 2013

Solution one: Do it via the focus event. Not the best solution.

public static void main(final String[] args) {
    // simple window preparation
    final JFrame f = new JFrame();
    f.setBounds(200, 200, 400, 400);
    f.setVisible(true);

    { // this sleep part shall simulate a user doing some stuff
        try { 
            Thread.sleep(2345);
        } catch (final InterruptedException ignore) {}
    }

    { // here's the interesting part for you, this is what you put inside your button listener or whatever
        final JTextField t = new JTextField("Hello World!");
        t.addFocusListener(new FocusListener() {
            @Override public void focusLost(final FocusEvent pE) {}
            @Override public void focusGained(final FocusEvent pE) {
                t.selectAll();
            }
        });
        f.add(t);
        f.validate();

        t.requestFocus();
    }
}