Java JTextField Focus makeSureUserGetsFocus(final JTextField field)

Here you can find the source of makeSureUserGetsFocus(final JTextField field)

Description

Forces focus to a particular JTextField in a displayed dialog

License

Open Source License

Parameter

Parameter Description
field The field to force into focus

Declaration

private static void makeSureUserGetsFocus(final JTextField field) 

Method Source Code

//package com.java2s;
import javax.swing.*;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

public class Main {
    /**// w  w  w. j  a  v  a2  s.  co  m
     * Forces focus to a particular JTextField in a displayed dialog
     *
     * @param field The field to force into focus
     */
    private static void makeSureUserGetsFocus(final JTextField field) {
        //from http://stackoverflow.com/questions/14096140/how-to-set-default-input-field-in-joptionpane
        field.addHierarchyListener(new HierarchyListener() {
            HierarchyListener hierarchyListener = this;

            @Override
            public void hierarchyChanged(HierarchyEvent e) {
                JRootPane rootPane = SwingUtilities.getRootPane(field);
                if (rootPane != null) {
                    final JButton okButton = rootPane.getDefaultButton();
                    if (okButton != null) {
                        okButton.addFocusListener(new FocusAdapter() {
                            @Override
                            public void focusGained(FocusEvent e) {
                                if (!e.isTemporary()) {
                                    field.requestFocusInWindow();
                                    field.removeHierarchyListener(hierarchyListener);
                                    okButton.removeFocusListener(this);
                                }
                            }
                        });
                    }
                }
            }
        });
    }
}

Related

  1. addListenerToCommitOnFocusLost(final JTextField field)
  2. addNewFocusListenerForTextField(final JTextField textField, final Runnable r)
  3. attachListenerOnLabelClickFocusTextElement(JLabel label, final JTextField textField)
  4. clearOnFocus(final JTextField jtf, final String onlyInText)
  5. configureFocusActionKeys(JTextField textField, boolean primary)
  6. minimoCaracteres(JTextField txt, FocusEvent e, int pValor)