关闭JDialog时没有WindowEvent

时间:2012-03-01 16:01:07

标签: java swing jdialog windowlistener

我在JFrame中显示JDialog。这个JDialog在处理时什么都不做。我想抓住结束事件并显示一个Popup但没有任何反应。

我找不到错误。你能告诉我问题出在哪里吗?

非常感谢!

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) {}
    }
}

1 个答案:

答案 0 :(得分:7)

您忘记将WikiLowner添加到JDialogTest类中,以捕获WINDOW CLOSING事件。像这样:

addWindowListener(this);

此外,在JDialogTest类中调用setVisible(true),在JFrameTest类中创建JDialogTest类的对象时调用另一次。

请不要在Swing中使用任何setXXXSize(...)方法,让布局管理器担心该部分。此外,如果您使用setLocationByPlatform(true)而不是setLocationRelativeTo(null),那将是明智之举。关于为什么应该使用前者而不是后者的一个很好的例子是由@Andrew Thompson在{Threads for How to best position Swing GUI's

中给出的