2012-03-01 64 views
4

我在一個JFrame中顯示一個JDialog。這個JDialog在處理時不做任何事情。我想趕上結束事件並顯示一個Popup,但沒有任何反應。我找不到這個bug。你能告訴我問題在哪裏嗎?關閉一個JDialog沒有WindowEvent

非常感謝!

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

回答

7

你忘了addWindowListener您JDialogTest類,趕上WINDOW CLOSING事件。事情是這樣的:

addWindowListener(this); 

而且你要把JDialogTest類和其他的時間裏面調用setVisible(true)一旦在創建JFrameTest類的內部JDialogTest類的對象。

請不要在Swing中使用任何setXXXSize(...)方法,讓Layout Manager擔心該部分。此外,如果您使用setLocationByPlatform(true)而不是setLocationRelativeTo(null)將是明智之舉。關於爲什麼前者應該被用來代替後者的一個很好的例子是@Andrew Thompson在本文中爲How to best position Swing GUI's

+0

非常感謝您的幫助!是的,我忘了addWindowListener(this);其餘的,這只是一個[SSCCE](http://sscce.org/)向你展示我的問題。但無論如何,感謝您的建議。 – Maxbester 2012-03-02 09:30:01

+0

@ user902025:您的歡迎和保持微笑:-) – 2012-03-02 09:32:20