2016-04-26 60 views
2

我創建了一個從WindowAdapter擴展的類,這樣每次我想關閉一個窗口時,它會問你是否真的要關閉窗口。當我點擊「否」時出現問題。我該如何處理它,以便窗口事件不會「保持」在那裏,並且框架一直在嘗試分派它? 我只做一個回報,我不能拿出任何東西。下面的代碼:WindowAdapter發送一個窗口事件(關閉窗口)

public class ExitController extends WindowAdapter{ 

    @Override 
    public void windowClosing(WindowEvent windowEvent) { 
     if(JOptionPane.showConfirmDialog(null,"Are you sure to close this window?", 
     "Really Closing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) 
     == JOptionPane.YES_OPTION){ 
        System.exit(0); 
       } else { 
        return; 
       } 
      } 
     } 
+0

你在這裏做什麼應該工作。其他聽衆也會收到該事件。 –

回答

1

的問題是在JFrame.processWindowEvent

protected void processWindowEvent(WindowEvent e) { 
    super.processWindowEvent(e); // --> this will call your listener 

    if (e.getID() == WindowEvent.WINDOW_CLOSING) { 
     switch(defaultCloseOperation) { 
      case HIDE_ON_CLOSE: 
      setVisible(false); 
      break; 
      case DISPOSE_ON_CLOSE: 
      dispose(); 
      break; 
      case DO_NOTHING_ON_CLOSE: 
      default: 
      break; 
      case EXIT_ON_CLOSE: 
       // This needs to match the checkExit call in 
       // setDefaultCloseOperation 
      System.exit(0); 
      break; 
     } 
    } 
} 

獨立的監聽器做什麼時,JFrame評估其defaultCloseOperation並關閉或隱藏自身。

因此,您需要也初始化架在其上安裝監聽器,以防止默認操作權默認關閉操作:

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 
frame.addWindowListener(new ExitController()); 

你可以在ExitListener提供一種方法,以促進這一點:

public class ExitController extends WindowAdapter { 
    public void installOn(JFrame frame) { 
     frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 
     frame.addWindowListener(this); 
    } 
+0

我已經做到了。問題的確在於,當我與界面交互並且面板發生變化時,返回調用會遍歷所有這些並繼續顯示確認對話框(新的彈出窗口),以嘗試分派相同的(窗口)事件。有什麼方法可以使用它或什麼? – jari

+0

@Jari你應該添加一個小例子程序到你的問題,它演示的效果... – wero

+0

它似乎並沒有工作......它說「方法消耗()從類型AWTEvent不可見」。 – jari

2

結帳Closing an Application

它給出了一些基本的代碼。基本代碼會將幀的默認關閉操作設置爲DO_NOTHING_ON_CLOSE

然後在WindowListener中,當用戶確認關閉時,它會將默認關閉操作重置爲EXIT_ON_CLOSE而不是使用System.exit(0);

您還可以使用CloseListener類,它是您的ExitController類的更復雜的版本(因爲它提供更多的功能)。