组件图形中的空指针异常

时间:2013-04-27 15:05:28

标签: java swing graphics nullpointerexception jcomponent

我有DrawOutput类,它扩展了JComponent。 this.getGraphics我传递给paint在这里是null。我怎样才能获得这门课的Grapics?

public class DrawOutput extends JComponent {

这是类的构造函数。

 DrawOutput (MinDistances requiredMinDistances, MainMatrix matrix){
            super();
            getRequiredMedoidsArray(requiredMinDistances);
            paint(this.getGraphics(), requiredMinDistances, matrix);
        }

这里的内容为空

  public void paint(Graphics content, MinDistances requiredMinDistances, MainMatrix matrix)        {
    ...

}

private float[] setColor (int colorID){
           float[]hsbValues=new float[3];
    if(colorID == 1){
        hsbValues =  Color.RGBtoHSB(0,255,255,hsbValues);
    }
    else if(colorID == 2){
        hsbValues =  Color.RGBtoHSB(255,0,255,hsbValues);
    }
    else if(colorID == 3){
        hsbValues =  Color.RGBtoHSB(0,255,0,hsbValues);
    }
    else if(colorID == 4){
        hsbValues =  Color.RGBtoHSB(255,255,0,hsbValues);
    }
    else if(colorID == 5){
        hsbValues =  Color.RGBtoHSB(255,0,0,hsbValues);
    }
    else if(colorID == 6){
        hsbValues =  Color.RGBtoHSB(255,255,255,hsbValues);
    }
    else{
        hsbValues =  Color.RGBtoHSB(0, 0, 0,hsbValues);
    }
    return hsbValues;
}

private void getRequiredMedoidsArray(MinDistances distancesCell){
   ...
}

}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

不要在构造函数中执行此操作,在绘画中保持痛苦,或使用活动渲染进行绘制。

我的建议是

  1. 在构造函数中创建一个BufferedImage。
  2. 随时在BufferedImage上绘图。
  3. 将BufferedImage绘制到绘画中的屏幕。
  4. 全球状态:

    BufferedImage offscreen;
    Graphics offscreenGraphics;
    

    在构造函数中:

    offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    offscreenGraphics = offscreen.getGraphics();
    

    然后你可以随时随地使用offscreenGraphics。

    然后在油漆中:

    g.drawImage(offscreen, 0, 0, width, height, null);
    

    希望这有帮助。