AWT 窗口关闭侦听器/事件

2022-09-02 01:03:27

我很抱歉,如果这是一个n00b问题,但是一旦我创建了Window监听器,窗口事件和其他所有内容,我就花了很长时间,我如何指定要调用的方法?这是我的代码:

private static void mw() {
    Frame frm = new Frame("Hello Java");
    WindowEvent we = new WindowEvent(frm, WindowEvent.WINDOW_CLOSED);
    WindowListener wl = null;
    wl.windowClosed(we);
    frm.addWindowListener(wl);
    TextField tf = new TextField(80);
    frm.add(tf);
    frm.pack();
    frm.setVisible(true);

}

我试图获取一个URL,并下载它,我已经解决了其他所有问题,我只是想让窗口关闭。


答案 1

Window closing method

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class FrameByeBye {

    // The method we wish to call on exit.
    public static void showDialog(Component c) {
        JOptionPane.showMessageDialog(c, "Bye Bye!");
    }

    public static void main(String[] args) {
        // creating/udpating Swing GUIs must be done on the EDT.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                final JFrame f = new JFrame("Say Bye Bye!");
                // Swing's default behavior for JFrames is to hide them.
                f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                f.addWindowListener( new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent we) {
                        showDialog(f);
                        System.exit(0);
                    }
                } );
                f.setSize(300,200);
                f.setLocationByPlatform(true);
                f.setVisible(true);

            }
        });
    }
}

还要查看 Runtime.addShutdownHook(Thread), 了解在关闭之前执行的任何至关重要的操作。

断续器

下面是该代码的 AWT 版本。

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

class FrameByeBye {

    // The method we wish to call on exit.
    public static void showMessage() {
        System.out.println("Bye Bye!");
    }

    public static void main(String[] args) {
        Frame f = new Frame("Say Bye Bye!");
        f.addWindowListener( new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                showMessage();
                System.exit(0);
            }
        } );
        f.setSize(300,200);
        f.setLocationByPlatform(true);
        f.setVisible(true);
    }
}

答案 2

此示例演示如何与 WindowAdapter 一起使用,WindowListener 接口的具体实现。另请参见如何编写窗口侦听器addWindowListener()