No WindowEvent when closing JDialog

I am showing JDialog in a JFrame. This JDialog does nothing. I would like to catch a close event and display a popup, but nothing happens.

I can not find the error. Could you tell me where the problem is?

Thanks a lot!

import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.Window; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextArea; @SuppressWarnings("serial") public class JFrameTest extends JFrame { public JFrameTest() { setLayout(new FlowLayout()); setSize(300, 300); add(new JTextArea("This is a text")); setDefaultCloseOperation(JFrameTest.EXIT_ON_CLOSE); getContentPane().setPreferredSize(getSize()); pack(); setLocationRelativeTo(null); setVisible(true); JDialogTest dialog = new JDialogTest(this, Dialog.ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } public static void main(String[] args) { new JFrameTest(); } private class JDialogTest extends JDialog implements WindowListener { public JDialogTest(Window parent, ModalityType modalityType) { super(parent, modalityType); setLayout(new FlowLayout()); add(new JLabel("This is another text")); setSize(200, 50); setDefaultCloseOperation(JDialogTest.DO_NOTHING_ON_CLOSE); setLocationRelativeTo(null); getContentPane().setPreferredSize(getSize()); pack(); setVisible(true); } @Override public void windowActivated(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) { JOptionPane.showMessageDialog(this, "A popup message!"); } @Override public void windowDeactivated(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} @Override public void windowOpened(WindowEvent e) {} } } 
+4
source share
1 answer

You forgot to add a WindowListener to your JDialogTest class to catch the WINDOW CLOSING event. Something like that:

 addWindowListener(this); 

In addition, you call setVisible(true) once in your JDialogTest class, and at another time you create an object of the JDialogTest class inside the JFrameTest class.

Please, never use any setXXXSize (...) method in Swing, let Layout Manager worry about this part. Moreover, it would be wise to use setLocationByPlatform(true) instead of setLocationRelativeTo(null) . A good example of why the former should be used instead of the latter is @Andrew Thompson, in this topic for How to Best Position the Swing GUI

+7
source

Source: https://habr.com/ru/post/1399214/


All Articles