0

I just want the JDialog to close if I click out of the JDialog

import javax.swing.JDialog;
import javax.swing.JLabel;


public class DialogFenster extends JDialog {

    public DialogFenster(String pText, String pTitel)
    {
        JDialog meinJDialog = new JDialog();
        meinJDialog.setTitle(pTitel);
        meinJDialog.setBounds(800, 500, 300, 70);
        meinJDialog.setModal(true);
        meinJDialog.add(new JLabel(pText));
        meinJDialog.setVisible(true);
    }
}
Acapulco
  • 3,373
  • 8
  • 38
  • 51
  • 1
    That won't work as there is nothing receiving the click event, and as the dialog is modal nothing else in your app can receive any events. – mwarren Dec 16 '19 at 15:26
  • https://stackoverflow.com/questions/6969164/button-for-closing-a-jdialog – Ali Beyit Dec 16 '19 at 15:27
  • 1
    Make it non modal and intercept onFocusLost. Possibly overlay the main JFrame with a half transparent gray panel receiving the click. – Joop Eggen Dec 16 '19 at 16:21
  • It sounds like you may want a [Popup](https://docs.oracle.com/en/java/javase/13/docs/api/java.desktop/javax/swing/PopupFactory.html#getPopup%28java.awt.Component,java.awt.Component,int,int%29) rather than a JDialog. – VGR Dec 16 '19 at 17:28

1 Answers1

0

You can use a WindowListener in order to know whether the dialog has lost its focus:

JDialog dialog = new JDialog(frame, false);//false for not modal
dialog.addWindowListener(new WindowAdapter() {
    public void windowDeactivated(WindowEvent e) {
        dialog.dispose();
    }
});
dialog.setVisible(true);

But it must be a non-modal dialog. If it is modal windowDeactivated will never be called.

George Z.
  • 6,643
  • 4
  • 27
  • 47