我在某些代码中发现了渲染错误,并找到了解决方法,但我想知道为什么我会得到不同的行为。在旧代码中,背景(有时)会呈现为白色,尽管在调试时 getBackground()
会返回正确的颜色。
旧代码:
@Override
public void paint(Graphics g) {
// Stuff
g.setColor(getBackground());
g.clearRect(0, 0, width, height); // Obviously wrong.
// More stuff
}
新代码:
@Override
public void paint(Graphics g) {
// Stuff
g.setColor(getBackground());
g.drawRect(0, 0, width, height); // Correct usage with 'setColor' call.
// More stuff
}
正如我输入的代码,很明显 setColor(getBackground())
对 clearRect(...)
调用没有影响。但我假设调用 clearRect(...)
并调用 setColor(getBackground())
,然后调用 drawRect(...)
将语义相同。
我也考虑了不透明属性,但是父轻量级组件和祖先重量级组件都使用相同的背景颜色,并且很明显该组件是行为不正确的组件(它是 8 个组件之一)其父级拥有相同类型的组件 - 但只有到达此代码部分的组件才会出现问题)。
如果有帮助的话,我正在使用 JDK 1.6.0_07(当然是出于商业原因)。
最佳答案
这是来自 JavaDocs 的信息 -
Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode.
Beginning with Java 1.1, the background color of offscreen images may be system dependent. Applications should use setColor followed by fillRect to ensure that an offscreen image is cleared to a specific color.
正如这所暗示的,clearRect 是系统相关的,并且不考虑 getBackground() 的值。
关于java - Graphics.clearRect 和 Graphics.drawRect 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5879884/