我有时会看到以下堆栈跟踪运行使用 UISpec4j 构建的测试
java.lang.ClassCastException: org.uispec4j.interception.toolkit.Empty$DummyGraphics2D cannot be cast to sun.java2d.SunGraphics2D
at java.awt.Component$BltBufferStrategy.getDrawGraphics(Component.java:4348)
at javax.swing.BufferStrategyPaintManager.prepare(BufferStrategyPaintManager.java:522)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:276)
at javax.swing.RepaintManager.paint(RepaintManager.java:1265)
at javax.swing.JComponent._paintImmediately(JComponent.java:5167)
at javax.swing.JComponent.paintImmediately(JComponent.java:4978)
at javax.swing.JComponent.paintImmediately(JComponent.java:4990)
at javax.swing.AbstractButton.doClick(AbstractButton.java:371)
...
根本原因似乎是顽皮的JDK代码对SunGraphics2D而不是java.awt.Graphics2D进行了向下转换java.awt.Component.BltBufferStrategy.getDrawGraphics()
/**
* @return the draw graphics
*/
public Graphics getDrawGraphics() {
revalidate();
Image backBuffer = getBackBuffer();
if (backBuffer == null) {
return getGraphics();
}
SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics();
g.constrain(-insets.left, -insets.top,
backBuffer.getWidth(null) + insets.left,
backBuffer.getHeight(null) + insets.top);
我做错了什么,因为我在其他地方找不到任何参考资料..?
解决方法?我能想到的就是在我的测试中吞下异常,并不理想。
这似乎是JDK的一个未记录的功能,只有在UISpec4J测试框架中使用不同的Graphics2D实现时才会暴露。
进一步的调试显示,这只发生在某些使用加速的平台上。如果启用了双缓冲,则通过 javax.swing.JComponent._paintImmediately(int、int、int、int( 的路由会有所不同,引发异常
作为解决方法,可以通过以下方法禁用此功能,从而避免异常
RepaintManager.currentManager(null).setDoubleBufferingEnabled(false);