强制JTextField在出现时选择其所有内容

时间:2013-01-02 12:19:02

标签: java swing jtextfield

我有一个JLabel当你点击它时被JTextField取代,我需要JTextField自动选择它出现时的所有文字。

感谢分配给我们的帮助。

3 个答案:

答案 0 :(得分:9)

解决方案一:通过焦点事件来做。不是最好的解决方案。

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();
    }
}

答案 1 :(得分:6)

JTextField.selectAll()就是您所需要的。

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();
            }
        });
    }
}

答案 2 :(得分:2)

JTextField类在其API中包含用于此的方法。

这可以提供帮助:

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