10

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

narendra-choudhary
  • 4,582
  • 4
  • 38
  • 58
Benjamin Albert
  • 738
  • 1
  • 7
  • 19
  • Is what you are looking for? http://stackoverflow.com/questions/1178312/how-to-select-all-text-in-a-jformattedtextfield-when-it-gets-focus/1178596#1178596 – SomeJavaGuy Jan 02 '13 at 12:21
  • I tried this both before I asked this question, the problem with this answer is that it did not work. also the other problem with this answer is that the text field gains focus only after you click the text it, and not when it appears – Benjamin Albert Jan 02 '13 at 12:34
  • See http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html on how to give focus to a Swing component – Wim Deblauwe Jan 02 '13 at 12:48
  • update your code what you've tried then its easy to fix – vels4j Jan 02 '13 at 12:58

3 Answers3

11

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();
    }
}
JayC667
  • 2,418
  • 2
  • 17
  • 31
  • 1
    What's the purpose of using Thread.sleep? This is normally considered bad practice within a Swing application – MadProgrammer Jan 02 '13 at 21:07
  • That was just to have the field pop up after a delay, instead of doing all this click-button-hides-element-newelement-pop-sup-getsfocus-all-is-selected that he was talking about in the original question. But I'll edit my post so it's clearer. – JayC667 Jan 04 '13 at 12:11
  • > Not the best solution Why? What is wrong with this solution, can you elaborate? – Samuel Yvon Jan 26 '21 at 18:45
  • @MadProgrammer oh btw now that I see that, I got a follow-up question: When you said 'Thread.sleep() in Swing is bad practice', you actually meant Thread.sleep() inside the EDT, or blocking it in any other way, right? – JayC667 Jan 27 '21 at 05:30
  • @JayC667 You're also initialising the UI out side of the EDT, which is not a good idea, but I appreciate that this meant only as a demonstration of the concept – MadProgrammer Jan 27 '21 at 08:54
8

JTextField.selectAll() is what you need.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SelectAll
{
    private int count = 0;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Select All");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        final JPanel contentPane = new JPanel();
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                JTextField tfield = new JTextField(10);
                tfield.setText("" + (++count));             
                contentPane.add(tfield);
                tfield.requestFocusInWindow();
                tfield.selectAll();

                contentPane.revalidate();
                contentPane.repaint();
            }
        });

        contentPane.add(addButton);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    public static void main(String... args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new SelectAll().displayGUI();
            }
        });
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • Seems like you have to use selectAll() in conjunction with [requestFocusInWindow()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocusInWindow()), to get the desired effect. As shown in my edit. – nIcE cOw Jan 02 '13 at 13:07
2

The JTextField class contains methods in its API for this.

This can help:

http://forums.codeguru.com/showthread.php?308517-How-do-you-highlight-the-text-in-a-JTextfield

TechSpellBound
  • 2,505
  • 6
  • 25
  • 36