0

I have DrawOutput class, which extends JComponent. this.getGraphics whic I pass to paint is null here. How can I get Grapics of this class?

public class DrawOutput extends JComponent {

Here is constructor of class.

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

content is null here

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

}

Any suggestions?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
dat_dude
  • 67
  • 6
  • 1
    maybe you should override `paint()` and wait until it is called automatically? – micha Apr 27 '13 at 15:08
  • "Swing programs should override `paintComponent()` instead of overriding `paint()`."—[*Painting in AWT and Swing: The Paint Methods*](http://www.oracle.com/technetwork/java/painting-140037.html#callbacks). – trashgod Apr 27 '13 at 16:46

1 Answers1

0

Do not do it in the constructor, keep the paining in the paint, or do the painting using active rendering.

My suggestion is

  1. Create a BufferedImage in constructor.
  2. Draw on the BufferedImage whenever you want.
  3. Draw the BufferedImage to screen in paint.

Global state:

BufferedImage offscreen;
Graphics offscreenGraphics;

In constructor:

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

then you can just draw on offscreenGraphics whenever you want without issue.

Then in paint:

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

Hope this helps.

Dmytro
  • 5,068
  • 4
  • 39
  • 50