Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force JTextField to select all of its contents when it appears

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.

like image 756
Benjamin Albert Avatar asked Jan 02 '13 12:01

Benjamin Albert


2 Answers

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();
    }
}
like image 113
JayC667 Avatar answered Nov 15 '22 19:11

JayC667


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();
            }
        });
    }
}
like image 40
nIcE cOw Avatar answered Nov 15 '22 19:11

nIcE cOw