当您创建JFrame
实例时,您可以从此实例使用setBackground
方法。但是,无论您尝试在那里放置什么颜色,您都会收到灰色背景颜色。
发生这种情况(据我所知),因为默认的 JPanel
实例是在 JFrame
内部自动创建的,并覆盖在它上面。因此,要获取颜色设置,您需要调用
JFrame.getContentPane().setBackground(Color.RED);
实际上调用了 JPanel
的 setBackground
,该默认 JPanel
存在于 JFrame
中。
我也尝试下一步:
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。
问题:
为什么
jf.getContentPane().setSize(300, 100);
不调整默认JPanel
的大小,从而显示JFrame
背景?为什么 JFrame 有
setBackground
方法,如果无论如何你都看不到它并且它一直被默认的JPanel
覆盖?
最佳答案
根据JFrame
的类层次结构如下所示:
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
方法Frame#setBackground()继承自 Frame和 JFrame不会覆盖它。
什么JFrame状态:
<小时/>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()
,如下所示:
@Override
public void setBackground(Color color){
super.setBackground(color);
getContentPane().setBackground(color);
}
关于java - JFrame setBackground 的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213483/