JFrame setBackground的目的是什么 [英] what is the purpose of 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);
实际调用默认值JPanel
的setBackground
的
,它存在于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 :
-
为什么
jf.getContentPane().setSize(300, 100);
不调整默认大小JPanel
的大小,却显示了JFrame
背景?
Why
jf.getContentPane().setSize(300, 100);
does not resize defaultJPanel
, revealingJFrame
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
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, aJFrame
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 theJFrame
. 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屋!