【问题标题】:Cannot change the background color of JFrame ContentPane无法更改 JFrame ContentPane 的背景颜色
【发布时间】:2016-11-27 00:00:10
【问题描述】:

所以我在 java 中有一个蛇程序,运行良好,但是在我的 Frame 类中,我无法更改 JFrame 的内容窗格的背景颜色,我使用 getContentPane().setBackground(Color.DARK_GRAY); 但它不工作,有什么帮助吗?

这是我的Frame 课程:

package mainpackage;

import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JFrame;

public class Frame extends JFrame {

    private static final long serialVersionUID = 1L;

    public Frame() {

        getContentPane().setBackground(Color.BLACK); \\NOT WORKING !!
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Snake by Sarp~");
        setResizable(false);
        init();
    }

    public void init() {
        setLayout(new GridLayout(1, 1, 0, 0));


        Screen s = new Screen();
        add(s);

        pack();

        setLocationRelativeTo(null);
        setVisible(true);
    }

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

}

【问题讨论】:

    标签: java swing jframe awt contentpane


    【解决方案1】:
    setLayout(new GridLayout(1, 1, 0, 0));
    

    使用上述布局管理器,您添加到框架的任何组件都将完全覆盖内容窗格。

    Screen s = new Screen();
    add(s);
    

    您可以设置内容窗格的背景,然后将组件添加到内容窗格。因此,您将在内容窗格顶部看到 Screen 组件的颜色。

    将 Screen 对象的颜色设置为您想要的任何颜色:

    s.setBackground( Color.BLACK );
    

    【讨论】:

    • @YoungMillie,这就是我的观点。他在内容窗格的顶部添加了一个组件。
    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2013-03-14
    • 2016-10-04
    • 2014-09-25
    相关资源
    最近更新 更多