java - 无法理解 JPanel setBackground 方法行为

标签 java swing overriding jlabel paintcomponent

JPanel.setBackground方法不执行任何操作(尽管 opaque 属性为 true )如果 super.paintComponent父方法未被调用。

我在这里阅读了很多关于此问题的类似问题,在每个问题中我只找到了没有解释的解决方案,帮助我理解了原因 setBackground在添加 JPanel 之前编写的方法至JFrame更改 JPanel背景颜色,而当 setBackground里面写着paintComponent没有任何改变(仅当调用父亲的 paintComponent 方法时,如前所述)。 它与Graphics有某种关系吗?对象?

我尝试更改JPanelopaque属性为true并使用 setBackground(COLOR.BLACK)paintComponent()我在扩展 JPanel 的类中重写的方法

  paintComponent(Graphics g)
    {
      this.setOpaque(true);
      this.setBackground(COLOR.BLACK);
    }

我预计JPanel背景颜色将为黑色

相反,背景颜色是默认颜色

最佳答案

首先,如果您使用 paintComponent(Graphics g) 方法,则需要包含的第一行是:super.paintComponent(g)否则你就会破坏油漆链。

这将允许父组件在您对其进行任何自定义之前绘制默认组件。如果你不这样做,那么,就像在一张纸上画画一样,想象一个圆圈,然后切割该圆圈,然后尝试绘制外部。

这是对How does super.paintComponent(g) works的更深入的回答

但是我不会写

this.setOpaque(true);
this.setBackground(COLOR.BLACK);

paintComponent(...) 方法内,因为它会被调用多次,并且您无法控制它何时被调用。我会将这些行放入构造函数中,除非您想稍后在程序中更改它,同时根据程序的状态或渐变进行绘制。

对于这部分:

why setBackground method when written before adding the JPanel to JFrame changes the JPanel background color

老实说,我不明白你的意思。

<小时/>

Why do you say that if i won't call super.paintComponent(),it will break the chain? It's still drawing all the shapes and lines i want using graphics object.

来自docs :

JPanel 有一个 UI 委托(delegate),它可以为自己执行背景绘制。您可以使用 super.paintComponent(g) 调用它,我们传递 Graphics 组件以防止不可撤销的更改,例如 Graphics.translate

您的 JPanel 知道如何绘制其子级,但需要一些帮助来绘制自身,而此帮助来自其父级。

当我提到“打破绘画链”时,我并不是说没有任何东西会绘画,而是你会得到奇怪的行为,例如 JPanel 的背景消失或未设置.

In addition,something weird happens if the argument i'm sending to setBackground method is a random color(using Random object). JPanel changing color very quickly although i'm not doing anything(not minimizing,not resizing,etc).Can you consider why?

正如我之前所说,paintComponent 会被调用多次,并且您无法控制何时调用它,即使移动鼠标或其他东西也会触发面板重新绘制。

关于java - 无法理解 JPanel setBackground 方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741741/

相关文章:

java - AsyncTask 中的 Volatile 和 Synchronized

java - 获取证书异常 : "No name matching localhost found" in Playframework java application

java - 使用 JFileChooser?按钮和限制文件类型

Java反射方法调用错误

java - 读取不同文件格式的策略模式

java - 空外键,在使用 hibernate [4.1.1] 注释的 ManyToOne 关系中

java - 将变量范围从一帧扩展到另一帧

java - JFilechooser 无法与选择按钮正常工作

c++ - 纯虚函数和覆盖函数 (c++)

python - Django 休息框架 : override create() in ModelSerializer passing an extra parameter