2011-11-01 69 views
3

我想通過WindowStateListener在單個Frame上收聽活動。爲什麼這個監聽器不能檢測窗口關閉事件?

import java.awt.Frame; 
import java.awt.Label; 

import java.awt.event.WindowStateListener; 
import java.awt.event.WindowEvent; 

public class UserInterface implements WindowStateListener 
{ 
    public static void main(final String[] arguments) 
    { 
     UserInterface userInterface = new UserInterface(); 
    } 

    public UserInterface() 
    { 
     Frame frame = new Frame("Graphics Example"); 
     frame.addWindowStateListener(this); 
     frame.add(new Label("Hello, world!"); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public void windowStateChanged(WindowEvent event) 
    { 
     System.out.println(event.paramString(); 
    } 
} 

它最適合最小化事件,但不能關閉事件。 WINDOW_CLOSING is definitely a valid WindowEvent valueit's definitely something that Frame can throw。那麼爲什麼它不被傳遞給windowStateChanged()

回答

4

您可以使用它。

frame.addWindowListener(new java.awt.event.WindowAdapter() 
{ 
public void windowClosing(WindowEvent winEv) 

}} 

這肯定會編譯。

class TestSnippet { 
    public static void main(Sring[] args) { 

     // START: copy/pasted snippet 
     frame.addWindowListener(new java.awt.event.WindowAdapter() 
     { 
     public void windowClosing(WindowEvent winEv) 

     }} 
     // END: copy/pasted snippet 
    } 
} 

(A路人注意事項)嗯,除了..

I:\proj\TestSnippet.java:7: ';' expected 
     public void windowClosing(WindowEvent winEv) 
                ^
I:\proj\TestSnippet.java:9: ')' expected 
     }} 
     ^
2 errors 

Tool completed with exit code 1 
+0

這肯定會compiled.In這個監聽器我們可以執行我們有任務時,我們關上窗戶做。 – SilentBomb

+0

好吧,現在我明白,你想說什麼。是的,這是寫。 – SilentBomb

+0

隨時編輯我的補充。但是,請同時修正片段(或者更加一般化)。指向'WindowListener'的指針+1。 –