wood burning stoves 2.0*
The moose likes Swing / AWT / SWT and the fly likes Focus in a JPopupMenu Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Focus in a JPopupMenu" Watch "Focus in a JPopupMenu" New topic

Focus in a JPopupMenu

Jeff Smith
Ranch Hand

Joined: May 04, 2001
Posts: 50
Hi, I'm having quite a bit of trouble getting the focus into a popup menu. Here's what I'm doing:

  • I created a JPopupMenu and added a JList as it's only component.
  • I created a JButton that when clicked on displays the popup menu.

  • What I want is for the popup menu to be displayed and the JList in the menu to have focus so the user can immediately just press the up and down arrows to go up and down through the items. The problem is that it doesn't have the focus. Instead you have to click once in the JList, then you can start moving up and down with the up and down arrows.
    I've tried everything I can think of. Calling list.requestFocus() in the button's actionEvent after the menu has been shown causes a NullPointerException and calling list.requestDefaultFocus() after the menu has been shown doesn't cause errors, but doesn't actually give the list focus.
    Here's my code, maybe you can tell me what I'm doing wrong (this is all just inside a main method in my test class):
Jagan Reddy

Joined: Nov 11, 2001
Posts: 7
Hi Jeff,

Instead of using list.requestDefaultFocus() use

menu.requestDefaultFocus(). I tried out and is working ..
Jagan Reddy.

Jeff Smith
Ranch Hand

Joined: May 04, 2001
Posts: 50
Thanks, I thought I'd tried everything, but apparently I hadn't... that worked great. :-)
Jeff Smith
Ranch Hand

Joined: May 04, 2001
Posts: 50
Ok, this is very odd. The first time I ran it with that code everything worked fine, but now it's not??? After I closed the program, and ran it again the menu didn't have focus. And then, without closing the program (just the menu), I clicked the button again to get the menu up, and whenever the mouse is moved within the bounds of the menu, NullPointerException's are thrown until the list recieves focus by actually clicking in it? Do you experience this same problem, or is it just me?
It is sorta covered in the JavaRanch Style Guide.
subject: Focus in a JPopupMenu
Similar Threads
Custom Button Problem
JPopupMenu or JMenu - neither is quite what I'm after.
A scrollable JList?
How to add popup menu on button