Java tutorial
//package com.java2s; /* (C) 2007 Stefan Reich (jazz@drjava.de) This source file is part of Project Prophecy. For up-to-date information, see http://www.drjava.de/prophecy This source file is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1. */ import javax.swing.*; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; public class Main { public static void focusOnOpen(final JComponent component) { /* final Window window = SwingUtilities.getWindowAncestor(component); if (window != null) window.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) { component.requestFocus(); window.removeWindowListener(this); } }); */ component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { component.requestFocusInWindow(); component.removeAncestorListener(this); } public void ancestorRemoved(AncestorEvent event) { } public void ancestorMoved(AncestorEvent event) { } }); } }