此方法(setSize、setDefaultCloseOperation...对于 HelloFrame 类型未定义

This method (setSize, setDefaultCloseOperation... is undefined for the type HelloFrame

我正在尝试制作 Hello World 的 swing 版本!!!在 GUI 中编程。但是我不断收到标题中提到的错误。这是我的代码:

import javax.swing.*;

public class HelloFrame
{

    public static void main(String[] args)
    {
        new HelloFrame();
    }

    public HelloFrame()
    {
        this.setSize(200, 100);
        this.setDefaultCloseOperation(
            JFrame.EXIT_ON_CLOSE);
        this.setTitle("Hello World!");
        this.setVisible(true);
    }
}

错误在:

    this.setSize(200, 100);
    this.setDefaultCloseOperation(
        JFrame.EXIT_ON_CLOSE);
    this.setTitle("Hello World!");
    this.setVisible(true);

我真的很感激一些答案。谢谢!

编辑 1:哦耶!我忘了说我正在使用 java.

在您的示例中,HelloFrame implicitly 扩展了 Object。结果,this 引用了 Object,它没有 JFrame 方法。相反,让 HelloFrame 包含 一个 JFrame,如下所示。另外,

  • 我添加了一个 JLabel 以在调用 pack() 后为框架提供一些显示内容。

  • Swing GUI 对象应该在 event dispatch thread.

  • 构建和操作

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;

/** @see  */
public class HelloFrame {

    private void display() {
        JFrame f = new JFrame("HelloFrame");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setTitle("Hello World!");
        f.add(new JLabel("Hello World! Hello World!"), JLabel.CENTER);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new HelloFrame()::display);
    }
}