Hiding a popup (javax.swing.Popup and PopupFactory)

Hiding a popup (javax.swing.Popup and PopupFactory)

Post by Karsten Wu » Sat, 29 Sep 2007 02:23:26


Hello!

I implemented a popup panel with a grid of JButtons on it to be
displayed when another JButton is pressed. It pretty much looks like a
JPopupMenu under a JButton, much like a JMenu with JMenuBar.

I used the following code:

//real popup button
final JButton btnGroup = new JButton("Popup JButton");

final JPanel pnPopup = new JPanel();
pnPopup.setLayout(new GridLayout(dimGrid.height, dimGrid.width));

//... fill pnPopup with some JButtons doing something, when done add
action to button to popup panel

ActionListener al =
new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
PopupFactory pf = PopupFactory.getSharedInstance();

//display panel right under the button (like a menu)
Point pt = btnGroup.getLocationOnScreen();
Popup pop = pf.getPopup(btnGroup, pnPopup, pt.x, pt.y +
btnGroup.getHeight());
pop.show();
}
};

btnGroup.addActionListener(al);

pnUserBar.add(btnGroup);

This is just examplary code. What happens is clear: Any time I press
the popup button, the panel with the X*Y buttons appears, cluttering
the screen.

Now my problem: I have no idea how hide the popup! Sure, use hide()
method, but when? At best, I want the exact behavior like a JMenu has
with the JMenuBar (or such).

Does anyone know how to accomplish that? How? Maybe someone even has
some code that I could modify, that would be of great help.

Otherwise I have to revert to displaying a JPopupMenu on button press,
which isn't as nice visually...

TIA
Karsten