gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:09:56 25 4
gpt4 key购买 nike

我正在尝试制作 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扩展对象。因此,this 引用一个 Object,它没有 JFrame 方法。相反,让 HelloFrame 包含一个 JFrame,如下所示。另外,

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

  • Swing GUI 对象应该event dispatch thread 上构建和操作。 .

enter image description here

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

/** @see https://stackoverflow.com/a/32016671/230513 */
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);
}
}

关于java - 此方法(setSize、setDefaultCloseOperation... 对于 HelloFrame 类型未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32016208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com