javaswingjpopupmenu

How to show a JPopupMenu without stealing focus?


I am writing a program in Java Swing and in this program there will be a search bar (which will be a JTextField), and when there is something typed into this field I want to display the search results in a popup menu directly underneath the search bar, like Google does. I haven't got to actually populating the menu with the search results (I currently have a test menu with fixed items), I am stuck on the problem that everytime a new character is typed into the field focus is taken away from the field and onto the popup menu. I am using

show(Component invoker, int x, int y)

to display the menu, with the invoker being the text field or the containing box. And as I said, everytime this function is called the popup menu takes the focus away from the text box which is a big problem. Instead of using this show method I could use these:

setLocation(int x, int y)
setVisible(boolean b)

However without an invoker the popup menu isn't shown relative to the search bar, and when I use setInvoker(Component invoker) I have the same problem as with the show method. I can't set the invoker during initialization because the invoker isn't visible then. So how do I create this popupMenu with an invoker without taking focus away from the search text field? Or is there a better way to do what I am trying to accomplish?


Solution

  • Have you tried requestFocusInWindow()? I think you need to give the focus back to the search text field at the end of the popup menu code. I assume you have some code to create the popup menu. Add searchTextField.requestFocusInWindow() to the end of this code. If this doesn't help, then I need more information. Some more code would help.