JFrame setBackground的目的是什么 [英] what is the purpose of JFrame setBackground

查看:54
本文介绍了JFrame setBackground的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建JFrame实例时,该实例具有setBackground方法.但是,无论您尝试将哪种颜色放到那里,都将获得灰色背景颜色.

When you create JFrame instance, you have setBackground method available from this instance. However, regardless to what color you try to put there, you`ll receive gray background color.

发生这种情况(据我了解),因为默认的JPanel实例是在JFrame内部自动创建的,并位于其上.因此,要设置颜色,您需要调用

This happens (as i understood), because default JPanel instance is automatically created inside JFrame and lays over it . So, to get color set, you need to call

JFrame.getContentPane().setBackground(Color.RED);

实际调用默认值JPanelsetBackground

,它存在于JFrame内部. 我还尝试了下一步:

that actually calls setBackground of default JPanel , that exists inside JFrame. I also tried to do next :

JFrame jf = new JFrame();

//I expect this will set size of JFrame and JPanel 
jf.setSize(300, 500);

//I expect this  to color JFrame background  yellow 
jf.setBackground(Color.yellow);

//I expect this to shrink default JPanel to 100 pixels high, 
//so 400 pixels of JFrame should became visible
jf.getContentPane().setSize(300, 100);

//This will make JPanel red
jf.getContentPane().setBackground(Color.RED);

在这组代码之后,我得到了JFrame大小的纯红色正方形,即300 x 500. 问题:

After this set of code, I am having solid red square of JFrame size , i.e. 300 x 500. Questions :

  1. 为什么jf.getContentPane().setSize(300, 100);不调整默认大小JPanel的大小,却显示了JFrame背景?

  1. Why jf.getContentPane().setSize(300, 100); does not resize default JPanel , revealing JFrame background?

为什么JFrame拥有setBackground方法(如果无论如何您都看不到它),并且默认情况下它一直被JPanel覆盖?

Why JFrame has setBackground method if anyway you cannot see it and it is covered by default JPanel all the time?

推荐答案

根据JFrame的类层次结构,如下所示:

As per the class hierarchies of JFrame as shown below:

java.lang.Object
    java.awt.Component
        java.awt.Container
            java.awt.Window
                java.awt.Frame
                    javax.swing.JFrame

方法 Frame JFrame 不会不要覆盖它.

The method Frame#setBackground() is inherited from Frame and JFrame doesn't do override it.

JFrame 指出:

What JFrame states:

JFrame类与Frame略有不兼容.与所有其他JFC/Swing顶级容器一样,JFrame包含 JRootPane 作为其唯一的子级.根窗格提供的内容窗格通常应包含JFrame显示的所有非菜单组件.这与AWT框架的情况不同.

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case.


您可以覆盖JFrame的默认setBackground(),如下所示:


You can override default setBackground() of JFrame as shown below:

@Override
public void setBackground(Color color){
    super.setBackground(color);
    getContentPane().setBackground(color);
}

这篇关于JFrame setBackground的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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