我在 Java (Eclipse) 中制作了一个带有面板的框架,应用程序在按下十字按钮时没有关闭

I have made a frame with panel in Java (Eclipse), the application does not close on pressing the cross button

这是我的第一个问题,如有错误请指正。

这是代码,我尝试制作一个带有面板的框架,但应用程序在按下关闭按钮时没有退出。

当我尝试将默认关闭操作设置为退出时,它显示了一个错误。

所以,请帮帮我。

import java.awt.*;

public class FramewithPanel {

    private Frame f;
    private Panel p;

    public FramewithPanel(String title){
        f = new Frame(title);
        p = new Panel();
    }

    public void LaunchFrame() {
        f.setSize(200,200);
        f.setBackground(Color.blue);
        f.setLayout(null);

        p.setSize(100,100);
        p.setBackground(Color.yellow);

        f.add(p);
        f.setVisible(true);
    }



    public static void main(String args[]) {
        FramewithPanel guiWindow = 
            new FramewithPanel("Frame with Panel");

        guiWindow.LaunchFrame();
    }
}

我猜您想使用 JFrame 而不是 Frame,因为 Frame 没有默认的关闭操作。相反,它根本不会关闭,只会生成类型为 WINDOW_CLOSING.

WindowEvent

所以你要么做

private JFrame f;

// and in the constructor
f = new JFrame(title);
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

f = new Frame(title);
f.addWindowListener(new WindowAdapter() {

    @Override
    public void windowClosing(WindowEvent e) {
        f.dispose();
    }

});

鉴于您提到您坚持使用 Frame 而不是替代方案 JFrame,最简单的解决方案是添加一个 WindowListener,如下所示:

f.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
});

瞧瞧!