Search code examples
javaswingjpopupmenu

How do I get a JPopupMenu to "shadow" a component consistently


I have a custom auto complete JTextField. I use the JPopupMenu to contain the selection. I want to pop the JPopupMenu right under the JTextField using this method.

Rectangle r = textField.getBounds();
popup.show(textField, (int)(r.getX()), (int)(r.getY() + textField.getHeight));
popup.setVisible(true);

It works when I put the component in a simple JFrame. But when I put the component in a complex layout with JScrollPane. The location becomes random and inconsistent. I'd like the popupMenu to "shadow" the textField in any condition. How do I achieve that? Thanks.


Solution

  • The popup location is relative to the parent component.

    popup.show(textField, 0, textField.getHeight());
    

    should place it right under the textField.