【问题标题】:How do I construct a JFrame child class?如何构造 JFrame 子类?
【发布时间】:2015-08-07 19:13:11
【问题描述】:

我正在尝试从JFrame 创建一个子类。我认为我做得对,但是当我运行它时,它会打开一个没有名称或背景颜色的空白窗口(我的 JPanel 类是背景。但是,我知道错误不存在,因为我注释掉了添加(@987654323 @) 并且窗口仍然没有名称)而且 eclipse 也没有显示任何语法错误。为什么这段代码不起作用?:

主类:

package ashwin.engine;
import javax.swing.*;
import java.awt.*; 
public class Execute {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                int[] bcolor = new int[3];
                bcolor[0] = 254;
                bcolor[1] = 0;
                bcolor[2] = 0;
                Window  wndw = new Window("Test", 1000, 1000, bcolor, true);

            } });

    }

}

JFrame 子类:

package ashwin.engine;
import javax.swing.*;
import java.awt.*; 
public class Window extends JFrame {
    Window(String name, int width, int length, int[] backgroundColor, boolean visible) {

        System.out.println("made it to frame class");

        setName(name);
        setVisible(visible);
        setSize(width, length);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        Display display = new Display(backgroundColor);


    }
}

编辑: 忘了提,它确实打印出我的调试语句“使其成为框架类”,不知道这是否有帮助,但我认为我应该指出它。

【问题讨论】:

  • 你确定 setName() 吗?如果我不得不猜测,我会说,你的意思是 setTitle() 来设置窗口的标题。设置背景应该是setBackground()。
  • @MPirious 你是对的。我的意思是setTitle。通常我构造一个 JFrame 对象并在构造函数中输入标题。我只是想那叫做“名字”。

标签: java swing graphics jframe


【解决方案1】:

您不应使用setName,而应使用setTitle。这将有效地在屏幕上显示名称。 对于后台,你应该使用getContentPane().setBackgroundColor(Color color)

chode 应该是这样的:

public class Execute {

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                final Color bcolor = new Color(254, 0, 0);

                final Window wndw = new Window("Test", 1000, 1000, bcolor, true);

            }
        });

    }

}

public class Window extends JFrame {
    Window(final String name, final int width, final int length, final Color backgroundColor,
            final boolean visible) {

        System.out.println("made it to frame class");
        this.setTitle(name);
        this.setSize(width, length);
        this.getContentPane().setBackground(backgroundColor);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(visible);

    }
}

【讨论】:

【解决方案2】:

将 setVisible 行设为最后一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多