为什么这个侦听器不会检测窗口关闭事件?

时间:2011-11-01 05:15:13

标签: java swing events awt windowlistener

我正在尝试通过Frame在单个WindowStateListener上收听活动。

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()

2 个答案:

答案 0 :(得分:5)

WindowStateListeners不会收到窗口关闭事件的通知。它们仅被通知窗口状态的更改,例如图标化或取消图标化。如果您想要关闭事件,请实现WindowListener(或扩展WindowAdapter)。本教程解释了它http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html

答案 1 :(得分: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
    }
}

(路人注意)好吧,除了......

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