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

前端 未结 6 2304
走了就别回头了
走了就别回头了 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 06:49

    As pajton noted in a previous comment, Popup is not a JComponent to which listeners can be readily bound. But, as its documentation states, "implementations of Popup are responsible for creating and maintaining their own Components to render [its subject] to the user."

    So in using it as your presentation mechanism, your Popup is going to have to present itself as an actual Swing component anyway. Have it register itself to that component. Have it hide itself when the component loses focus.

    import java.awt.FlowLayout;
    import java.awt.Frame;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.Popup;
    
    public class PopupTester extends JFrame {
        private static class MessagePopup extends Popup
            implements WindowFocusListener
        {
            private final JDialog dialog;
    
            public MessagePopup(Frame base, String message) {
                super();
                dialog = new JOptionPane().createDialog( base, "Message" );
                dialog.setModal( false );
                dialog.setContentPane( new JLabel( message ) );
            }
            @Override public void show() {
                dialog.addWindowFocusListener( this );
                dialog.setVisible( true );
            }
            @Override public void hide() {
                dialog.setVisible( false );
                dialog.removeWindowFocusListener( this );
            }
            public void windowGainedFocus( WindowEvent e ) {
                // NO-OP
            }
    
            public void windowLostFocus( WindowEvent e ) {
                hide();
            }
        }
    
        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();
              MessagePopup popup = new MessagePopup( popupTester, "Howdy" );
              popup.show();
            }
          });
          popupTester.add(new JButton("No Click Me"));
          popupTester.setVisible(true);
          popupTester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

提交回复
热议问题