使用UISpec4j的ClassCastException

时间:2017-03-19 03:32:54

标签: java swing uispec4j

我有时会看到以下使用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.Component.BltBufferStrategy.getDrawGraphics()中的java.awt.Graphics2D

    /**
     * @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);

我做错了什么,因为我在其他地方找不到任何引用..?

变通方法?我能想到的只是在我的测试中吞下异常,不理想。

1 个答案:

答案 0 :(得分:0)

这似乎是JDK的一个未记录的功能,只有在使用与UISpec4J测试框架不同的Graphics2D实现时才会公开

进一步调试显示,这仅发生在使用加速的某些平台上。通过javax.swing.JComponent._paintImmediately(int,int,int,int)的路由会有所不同,如果启用了双缓冲,则抛出异常

作为一种解决方法,可以使用以下方法禁用此功能,以避免异常

Error in pairs.default(x, gap = 0, lower.panel = panel.smooth, upper.panel = panel.cor,  : 
  non-numeric argument to 'pairs'