Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 626
Ariyan Avatar asked Dec 04 '22 20:12

Ariyan


1 Answers

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);
}
like image 182
dacwe Avatar answered Dec 15 '22 01:12

dacwe