Java Swing Focus selectAndFocus(JComponent component)

Here you can find the source of selectAndFocus(JComponent component)

Description

Select all text in a text component and focus it.

License

Open Source License

Parameter

Parameter Description
component the text component

Declaration

public static void selectAndFocus(JComponent component) 

Method Source Code


//package com.java2s;
/*/*from   www . j  a  v a 2 s  . co m*/
 * SwingHelper.java
 * This file is part of Portecle, a multipurpose keystore and certificate tool.
 *
 * Copyright ? 2007-2014 Ville Skytt?, ville.skytta@iki.fi
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.awt.Component;

import javax.swing.JComboBox;
import javax.swing.JComponent;

import javax.swing.text.JTextComponent;

public class Main {
    /**
     * Select all text in a text component and focus it.
     * 
     * @param component the text component
     */
    public static void selectAndFocus(JComponent component) {
        JTextComponent textComponent = null;
        if (component instanceof JTextComponent) {
            textComponent = (JTextComponent) component;
        }
        if (component instanceof JComboBox) {
            Component editorComponent = ((JComboBox<?>) component).getEditor().getEditorComponent();
            if (editorComponent instanceof JTextComponent) {
                textComponent = (JTextComponent) editorComponent;
            }
        }
        if (textComponent != null) {
            textComponent.select(0, textComponent.getText().length());
        }
        component.requestFocusInWindow();
    }
}

Related

  1. requestFocus(final JComponent comp)
  2. requestFocus(final JComponent component)
  3. requestFocus(final Window win, final Component comp)
  4. requestFocusInWindow(final Component c)
  5. selectAllOnFocusGained()
  6. setFocus(JComponent component)
  7. setFocusableRecursively(final JComponent component, final boolean focusable, final boolean childsOnly)
  8. setFocusOn(Component component)
  9. setFocusOrder(JComponent... components)