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

前端 未结 6 2183
走了就别回头了
走了就别回头了 2021-01-04 06:26

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 e
6条回答
  •  伪装坚强ぢ
    2021-01-04 07:02

    I know this is an old question but I really needed the Popup to work in my case. So I tried a few things and the following is my solution.

    Add a FocusListener to the component you add to the popup and program the focusLost event on that component to hide the popup when focus is lost. Call the requestFocus method on your component just after showing the popup.

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    
    import javax.swing.*;
    
    public class PopupTester extends JFrame {
        JButton myButton = new JButton("Click Me");
        JLabel myComponent = new JLabel("Howdy");
        Popup popup = null;
    
        public PopupTester() {
            setLayout(new FlowLayout());
            setSize(300, 100);
            add(myButton);
            add(new JButton("No Click Me"));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            myComponent.addFocusListener(new FocusAdapter() {
                public void focusLost(FocusEvent e) {
                    if (popup != null) {
                        popup.hide();
                    }
                }
            });
    
            myButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    if (popup != null) {
                        popup.hide();
                        popup = null;
                    }
    
                    Point location = myButton.getLocationOnScreen();
                    int y = (int) (location.getY() + myButton.getHeight());
                    int x = (int) location.getX();
                    popup = PopupFactory.getSharedInstance().getPopup(PopupTester.this, myComponent, x, y);
                    popup.show();
                    myComponent.requestFocus();
                }
            });
        }
    
        public static void main(String[] args) {
            PopupTester popupTester = new PopupTester();
            popupTester.setVisible(true);
        }
    }
    

提交回复
热议问题