How do you hide a Swing Popup when you click somewhere else.
Posted
by Casey Watson
on Stack Overflow
See other posts from Stack Overflow
or by Casey Watson
Published on 2010-04-05T21:34:17Z
Indexed on
2010/04/05
21:43 UTC
Read the original article
Hit count: 201
I have a Popup that is shown when a user clicks on a button. I would like to hide the popup when any of the following events occur:
- The user clicks somewhere else in the application. (The background panel for example)
- The user minimizes the application.
The JPopupMenu has this behavior, but I need more than just JMenuItems. The following code block is a simplified illustration to demonstrate the current usage.
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PopupTester extends JFrame {
public static void main(String[] args) {
final PopupTester popupTester = new PopupTester();
popupTester.setLayout(new FlowLayout());
popupTester.setSize(300, 100);
popupTester.add(new JButton("Click Me") {
@Override
protected void fireActionPerformed(ActionEvent event) {
Point location = getLocationOnScreen();
int y = (int) (location.getY() + getHeight());
int x = (int) location.getX();
JLabel myComponent = new JLabel("Howdy");
Popup popup = PopupFactory.getSharedInstance().getPopup(popupTester, myComponent, x, y);
popup.show();
}
});
popupTester.add(new JButton("No Click Me"));
popupTester.setVisible(true);
popupTester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
© Stack Overflow or respective owner