JFrame的背景颜色没有改变吗? [英] JFrame background color is not changing?

查看:91
本文介绍了JFrame的背景颜色没有改变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改JFrame的颜色,但是由于某种原因,它没有更改,并且保持默认的灰色?在添加所有面板和元素之前,这是我的代码.

I'm trying to change the color of my JFrame but for some reason it isn't changing and remains the default grey color? This is my code it's included before I've added all my panels and elements:

private static void guiApp()
{
    
    
    //frame 2
    frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame2.setLocation(100,50);
    frame2.setBackground(Color.red);
    

这可能是因为我在框架中添加了其他面板吗?我尝试使用panel.setBackground(Color.red)更改颜色,但是似乎没有颜色出现,所以如果我错过了一步或将代码包含在错误的位置,我会感到困惑.

Could this be because I've added other panels to the frame? I've tried changing the colors of those with panel.setBackground(Color.red) but no color seems to be appearing so I am confused if I've missed a step or included the code in the wrong spot.

推荐答案

内容窗格"框架的一个JPanel覆盖了整个框架.因此,您需要更改内容窗格的背景.

The "content pane" of the frame is a JPanel which covers the entire frame. So you need to change the background of the content pane.

frame.getContentPane().setBackground( Color.RED ):

使用顶级容器以便更好地了解框架的结构.

Read the section from the Swing tutorial on Using Top Level Container to better understand the structure of a frame.

这可能是因为我在框架中添加了其他面板吗?

Could this be because I've added other panels to the frame?

是的,面板默认情况下是不透明的,因此它们将在内容窗格的顶部绘制.您可以使这些面板不透明:

Yes, panels are opaque by default so they will paint on top of the content pane. You could make these panels non-opaque:

panel.setOpaque( false );
frame.add(panel, BorderLayout.CENTER);

现在您的子面板是透明的,因此将显示内容窗格的背景.

Now your child panel is transparent so the background of the content pane will show.

或者如果您使面板不透明(默认为默认状态),然后执行以下操作:

Or if you leave the panel opaque (which is is by default) and do:

panel.setBackground( Color.BLUE);
frame.add(panel, BorderLayout.CENTER);

然后将蓝色"面板将覆盖红色"内容窗格.

Then the "blue" panel will cover the "red" content pane.

这篇关于JFrame的背景颜色没有改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆