【问题标题】:This method (setSize, setDefaultCloseOperation... is undefined for the type HelloFrame此方法 (setSize, setDefaultCloseOperation... 未定义 HelloFrame 类型
【发布时间】:2015-11-08 01:44:29
【问题描述】:

我正在尝试制作 Hello World 的摇摆版本!!! 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。

【问题讨论】:

  • 请存档这个帖子。

标签: java swing user-interface jframe


【解决方案1】:

在您的示例中,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 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);
    }
}

【讨论】:

  • 我现在试试。
  • 有效!我将弄清楚如何添加某种按钮来触发 Hello World!东西。
  • 好的垃圾神。我会试试看。
  • 好的。谢谢。会试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 2016-06-07
  • 2021-06-19
相关资源
最近更新 更多