你还没有把JLabel放到一个有效容器里,所以返回Graphics为空。如果你要对组件作定制处理,好像一般需要重载paint(Graphics g)方法?在paint()方法中使用g.drawLine(x,y)等。

解决方案 »

  1.   

    上面的问题已经解决,但画的时候又有个问题,我重载paint后,每次repaint后画的东西全是闪一下就没了,如果直接调用paint就没有问题,这是什么原因呢,程序大概如下:
    public void paint(Graphics g){
      super.paint(g);
      paintPlay();
    }private void paintPlay(){
      Graphics g = this.getGraphics();
      //do some drawing...
    }
      

  2.   

    那你可能需要重载paintComponent(Graphics g)而不是paint(Graphics g)吧,关于JComponent的paint(Graphics g)的描述中有这么一句:A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent.
      

  3.   

    在Swing中定制自己的组件时,建议重载paintComponent(Graphics g)而不是重载paint(Graphics g),否则可能会出现你意想不到的错误效果,以下是我在java官方网站查到的原话,有疑问的时候到http://java.sun.com/docs 上寻找答案是不错的选择:)
    Note:  We recommend that you don't override or invoke the method that calls the paintXxx methods: the paint method. Although overriding paint is legitimate in non-Swing components, it's generally not a good thing to do in components that descend from JComponent. Overriding paint can confuse the painting system, which relies on the JComponent implementation of the paint method for correct painting, performance enhancements, and features such as double buffering.
      

  4.   

    如楼上所说,如果从Swing组件派生新的类一般覆盖paintCompoent方法
    另外一个问题是在你的paintPlay()方法中不要使用this.getGraphics()来得到新的Graphics对象。
    直接使用paintComponent(Graphics g)这个方法中的g参数就行了。