gpt4 book ai didi

java - JFrame setBackground 的目的是什么

转载 作者:行者123 更新时间:2023-12-02 05:44:35 24 4
gpt4 key购买 nike

当您创建JFrame实例时,您可以从此实例使用setBackground方法。但是,无论您尝试在那里放置什么颜色,您都会收到灰色背景颜色。

发生这种情况(据我所知),因为默认的 JPanel 实例是在 JFrame 内部自动创建的,并覆盖在它上面。因此,要获取颜色设置,您需要调用

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

实际上调用了 JPanelsetBackground ,该默认 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。问题:

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

  2. 为什么 JFrame 有 setBackground 方法,如果无论如何你都看不到它并且它一直被默认的 JPanel 覆盖?

最佳答案

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

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

方法Frame#setBackground()继承自 FrameJFrame不会覆盖它。

什么JFrame状态:

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(),如下所示:

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

关于java - JFrame setBackground 的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com