Java 组件图形中的空指针异常

Java 组件图形中的空指针异常,java,swing,graphics,nullpointerexception,jcomponent,Java,Swing,Graphics,Nullpointerexception,Jcomponent,我有DrawOutput类,它扩展了JComponent。我传递给paint的this.getGraphics在此为空。我怎样才能得到这门课的图形 public class DrawOutput extends JComponent { 这是类的构造函数 DrawOutput (MinDistances requiredMinDistances, MainMatrix matrix){ super(); getRequiredMedoidsAr

我有DrawOutput类,它扩展了JComponent。我传递给paint的this.getGraphics在此为空。我怎样才能得到这门课的图形

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){
   ...
}

}

有什么建议吗?

不要在构造器中进行绘制,将绘制保留在绘制中,或者使用活动渲染进行绘制

我的建议是

  • 在构造函数中创建一个BuffereImage
  • 随时可以在BuffereImage上绘制
  • 在绘画中绘制缓冲区图像到屏幕
  • 全球国家:

    BufferedImage offscreen;
    Graphics offscreenGraphics;
    
    在构造函数中:

    offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    offscreenGraphics = offscreen.getGraphics();
    
    然后,你可以在任何时候都可以在屏幕外画画,而不会有任何问题

    然后在油漆中:

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

    希望这有帮助。

    也许您应该重写
    paint()
    并等待它被自动调用?“Swing程序应该重写
    paintComponent()
    ,而不是重写
    paint()
    ”。