Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

focusGained() on JSpinner / JTextFields (select all text)

843804Jun 10 2003 — edited Mar 18 2008

Trying to implement it so that the text in my JSpinner / JTextField's are selected when it gains focus I implemented this class (modified version of one I found in this forum):
public class CommonUtilityMethods {

    private static FocusAdapter allTextSelector;

    // Ensures that all the text in a JTextComponent will be

    // selected whenever the cursor is in that field (gains focus):

    public static void setSelectAllFieldText(JComponent comp) {

        if (allTextSelector == null) {
            // Lazy initialization of one adapter for all components:
            allTextSelector = new java.awt.event.FocusAdapter() {
                public void focusGained(FocusEvent ev) {
                    if(ev.getSource() instanceof JTextComponent) {
                        JTextComponent textComp = (JTextComponent) ev.getSource();
                        textComp.selectAll();
                    } else if(ev.getSource() instanceof valueSpinner) {
                        valueSpinner vcomp = (valueSpinner)ev.getSource();
                        ((JSpinner.DefaultEditor )vcomp.getEditor ()).getTextField().selectAll();
                    }
                }
            };
        }
        comp.addFocusListener(allTextSelector);
    }
}
And then I add the listener using the setSelectAllFieldText method.

It does however not work as expected. On JTextField's a selection is only made the first time the textfield gains focus (so I get it to select all text if I remove the focus from the JInternalFrame which it is located in and then give it focus again).

On JSpinner no selection is made at all..

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Apr 15 2008
Added on Jun 10 2003
8 comments
953 views