Here you can find the source of makeSureUserGetsFocus(final JTextField field)
Parameter | Description |
---|---|
field | The field to force into focus |
private static void makeSureUserGetsFocus(final JTextField field)
//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); } } }); } } } }); } }