在试着做一个棋类程序,遇到问题如下:
定义一个名为ChessPanel的JPanel,在其paintComponent事件里用drawImage加载一幅棋盘图片
在上面覆盖一个透明的名为ActionPanel的透明JPanel(即setOpaque(false)),想在在这个JPanel上画棋子。可是覆盖上上透明ActionPanel后下面棋盘的图片就消失了,是否需要重绘底图?可是repaint函数不象paintComponent函数带有Graphics的参数。要如何获取graphics context? 查了文档应该是getGraphics()。可是在调用chessPanel.getGraphics()却返回空值,这是为什么?

解决方案 »

  1.   

    简单的说,就是我用JPanel的getGraphics()函数获取graphics context,结果返回null,可能是什么原因?如何解决?
      

  2.   

    我不熟悉SWING,不过你可以重载JPanel ,重写它的paint(Graphics g)方法
      

  3.   

    在paint的文档中说:
    Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing
    应该重载repaint而不是paint吧
      

  4.   

    若组件不可见,则getGraphics返回null。是否被覆盖在下层的JPanel就无法取得图形上下文了?