AWT window 侦听器没有响应

AWT window listener doesn't respond

我正在研究 AWT 和 swing,我开始使用一些简单的 GUI 来掌握 it.I 编写了以下代码,在我尝试关闭应用程序之前它运行良好并且它成功了'退出。

import java.awt.*;
import java.awt.event.*;

public class AWTCounter extends Frame{
    private Button button;
    private Label label;
    private TextField txt;
    private int count=0;
    public AWTCounter(){
        super("AWT Counter");
        addWindowListener(new WindowListener(){

            @Override
            public void windowActivated(WindowEvent arg0) {}

            @Override
            public void windowClosed(WindowEvent arg0) {
                System.out.println("closing time!");
                System.exit(0);
            }

            @Override
            public void windowClosing(WindowEvent arg0) {}

            @Override
            public void windowDeactivated(WindowEvent arg0) {}

            @Override
            public void windowDeiconified(WindowEvent arg0) {}

            @Override
            public void windowIconified(WindowEvent arg0) {}

            @Override
            public void windowOpened(WindowEvent arg0) {}

        });
        label = new Label();
        add(label);
        label.setText("Counter");
        txt = new TextField();
        txt.setEditable(false);
        add(txt);
        button = new Button("count");
        add(button);
        setSize(400,100);
        setLayout(new FlowLayout());
        setVisible(true);
        button.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                ++count;
                txt.setText(Integer.toString(count));
            }
        });

    }
    public static void main(String [] args){
        Thread t =new Thread(new Runnable(){
            public void run(){
                new AWTCounter();
            }
        });
        t.start();
    }
}

我 "registered" 源组件中的 WindowListener(在本例中为 AWTCounter,它是一个框架)并实现了我将要使用的唯一方法,但它从未响应......任何想法为什么会这样?

非常感谢大家!

请参阅 API for Frame - 对于 WINDOW_CLOSING 事件:"If the program doesn't explicitly hide or dispose the window while processing this event, the window close operation is canceled." - 如果将逻辑移至 windowClosing 方法,应用程序应退出。 Swing JFrame 更友好一些(如果您希望在关闭 JFrame 时退出应用程序而不需要 WindowListener,则可以将默认关闭行为设置为关闭时退出)。

最后但同样重要的是,我建议在 EventDispatchThread 上创建 GUI。例如:

public static void main(String [] args) throws Exception{
    Runnable t = new Runnable(){
        public void run(){
            new AWTCounter();
        }
    };
    SwingUtilities.invokeAndWait(t);
}

尝试这样做:

@Override
public void windowClosing(WindowEvent event) {
    System.exit(0); 
}