super.paintComponent(g)
做了什么(特别是当我们将它放在 paintComponent() 方法中时)?我很惊讶之前没有看到有人在 SO 中问过这个问题。
我翻出我关于 Java Graphics 的学校笔记,它在这行代码中唯一提到的是“不要删除”
。
然而,这几周我一直在练习和尝试使用 Java paintComponent() 方法。到目前为止,我还没有将该行包含到我的代码中,而且一切似乎都运行良好(到目前为止)。所以..
问题:
- 它有什么作用?
- 我们什么时候需要使用它?
- 把它写在paintComponent()里给我们带来什么好处?
最佳答案
- What does it do?
它会打印组件,就像您没有覆盖 paintComponent
方法一样。例如,如果您设置了背景颜色,这通常由您扩展的类绘制。
- When do we need to use it?
如果您不在整个组件上绘制,则可以使用它。您不绘制的部分将“发光”,这意味着您应该让父类(super class)绘制这些部分。以背景色为例:如果您只是在组件中间绘制一个圆圈,super.paintComponent
将确保在圆圈周围绘制背景色。
如果您确实绘制了组件的整个区域,那么您将绘制在任何 super.paintComponent 绘制的顶部,因此调用 super.paintComponent 是没有意义的。
- What advantage does it gives us by writing it in paintComponent()?
这是放置它的唯一合乎逻辑的地方。 paintComponent
在组件应该被绘制时被调用,并且如上文所述,如果您不自己绘制整个组件,则需要 super.paintComponent
来绘制发光的部分。
The documentation paintComponent
说得很好:
[...] if you do not invoker super's implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts.
关于java - super.paintComponent(g) 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28724609/