Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you hide a Swing Popup when you click somewhere else

Tags:

java

swing

popup

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:

  1. The user clicks somewhere else in the application. (The background panel for example)
  2. 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);
    }
}
like image 910
Casey Watson Avatar asked Apr 05 '10 21:04

Casey Watson


People also ask

How do I create a pop up window in Java Swing?

Java Program to create a popup and display it on a parent frame: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup.


1 Answers

Use a JPopupMenu. You can add any component to it, not just menu items.

like image 189
camickr Avatar answered Oct 18 '22 20:10

camickr