This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

Bug 91439 - Set Initial Focus feature for Swing form editing
Summary: Set Initial Focus feature for Swing form editing
Status: NEW
Alias: None
Product: guibuilder
Classification: Unclassified
Component: Code (show other bugs)
Version: 5.x
Hardware: All All
: P2 blocker with 2 votes (vote)
Assignee: issues@guibuilder
Keywords: UI
Depends on:
Reported: 2006-12-21 22:13 UTC by jhoffman
Modified: 2011-05-04 20:54 UTC (History)
1 user (show)

See Also:
Exception Reporter:


Note You need to log in before you can comment on or make changes to this bug.
Description jhoffman 2006-12-21 22:13:12 UTC
There should be a visual mechanism for setting focus to a component as was
implemented in Creator/Visual Web Pack.  It is simply a context menu item called
"Set Initial Focus".  When this item is selected, the component gets a small
annotation (a green triangle in the upper left corner), and the menu item is
changed to "Clear Initial Focus".  In the background, the appropriate call --
component.requestFocusInWindow() -- is added to the code.

The justification for this feature is that a well constructed desktop app will
set focus to a component when the window is initially displayed.  If you do not
explicitly set something to receive focus, then chances are it will appear as
though nothing has focus, or worse yet, something that shouldn't have focus
(like a toolbar button) will have the default focus and an errant keystroke by
the user could cause errors.

(See the Anagram sample in NB for an example of how this is done).
Comment 1 jhoffman 2006-12-21 22:15:18 UTC
Some related issues are 75811, 81626 (in mobility) and 68802 (in form)
Comment 2 Tomas Pavek 2007-01-02 11:06:32 UTC
Agree this is a useful enhancement.

Just the implementation is a bit trickier: component.requestFocusInWindow() in
initComponents() only works if the component is directly in the dialog or frame,
but not if it is in a panel that is added to some window later.
Comment 3 _ gtzabari 2011-05-04 20:54:32 UTC
Here is a simple implementation that will work for any Component, regardless of whether it is directly inside a Window or not:

class MyComponent extends JPanel
  public MyComponent()
    addHierarchyListener(new SetInitialFocus());

   * Sets the keyboard focus when the first time the panel becomes visible.
  private class SetInitialFocus implements HierarchyListener, WindowFocusListener
    public void hierarchyChanged(HierarchyEvent e)
      if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0 && getParent() != null)

    public void windowGainedFocus(WindowEvent e)
      foobar.requestFocusInWindow(); // ** Magic happens here **

    public void windowLostFocus(WindowEvent e)