Ariyan
Ariyan

Reputation: 15168

select all on focus in lots of jTextField

I have lots of jTextFields in my application (About 34 jTextFields) and I want all of them select all of their text when get focus and select none of text on focus lost.
Is there any way to do this with one listener or should I write a "FocusGained" and a "FocusLost" for each of these 34 jTextFields?

Thanks

Upvotes: 4

Views: 11843

Answers (4)

Robe
Robe

Reputation: 1

I would say the easy way to do it is add an action on click that simply selects all

private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {                                         
    jTextField1.selectAll();
}                      

Upvotes: -1

camickr
camickr

Reputation: 324207

Is there any way to do this with one listener

You can use the KeyboardFocusManager. See the example from Global Event Listeners.

Upvotes: 2

Pratik
Pratik

Reputation: 30855

Create on class and extend the JTextField now implement whatever you want in this class. And where you can create object of JTextField like this

JTextField txt1 = new JTextField();
frm.add(txt1);

instead of do this way

JTextField txt1 = new CustomText();
frm.add(txt1);

so you have to set the common class for the Text field

Upvotes: 2

dacwe
dacwe

Reputation: 43504

Create a class for this task:

static class FocusTextField extends JTextField {
    {
        addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                FocusTextField.this.select(0, getText().length());
            }

            @Override
            public void focusLost(FocusEvent e) {
                FocusTextField.this.select(0, 0);
            }
        });
    }
}

Example usage (code below):

screenshot

public static void main(String[] args) throws Exception {

    JFrame frame = new JFrame("Test");
    frame.setLayout(new GridLayout(5, 1));

    frame.add(new FocusTextField());
    frame.add(new FocusTextField());
    frame.add(new FocusTextField());
    frame.add(new FocusTextField());
    frame.add(new FocusTextField());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

Upvotes: 12

Related Questions