Search code examples
javaswinggraphicspaintcomponent

Graphics2D is returning "NULL" always


graphics2D is returning "NULL" always in below code. Due to that putPixel() method is not being called. I am calling PictureBox from form design.

public class PictureBox extends JPanel {

Graphics2D graphics2D;
static BufferedImage image;
int imageSize = 300;

public PictureBox(){
    setDoubleBuffered(false);
    this.setBorder(UIManager.getBorder("ComboBox.border"));
    this.repaint();     
}

public void paintComponent(Graphics g){

    super.paintComponent(g);
        if(image == null){  
            image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_RGB);
            graphics2D = (Graphics2D)image.createGraphics();
            graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            clear(); 
        }
          Graphics2D g2D = (Graphics2D) g;
          g2D.drawImage(image, 0, 0, this);
     repaint(); 
}

public final void putPixel(int x, int y, Color color) {
    if(graphics2D != null){
    graphics2D.setColor(color);
    graphics2D.drawLine(x, y, x, y);
    repaint();
    }
}
public void clear() {
    graphics2D.setPaint(Color.WHITE);
    graphics2D.fillRect(0, 0, imageSize,imageSize);
    repaint();
}

}

putPixel method is being called from main where i have (x,y) coordinate stored in Point2D array.


Solution

  • Since you have called putPixel from outside the class and you have not initialised the graphics2D and image in the constructor it may be that when you all calling putPixel method the class may not have been displayed. So you are getting graphics2D to be null as it initialises only when the paintComponent is called and it is called when this class gets displayed.

    The solution could be that you shift the initialisation code for the image and graphics2D to the constructor so that you do not encounter null while calling putPixel.

    NOTE

    You have indiscriminately called the method repaint(). You should keep in mind that repaint() calls paint() method which in turn calls paintComponent() method. So if you call repaint() inside paintComponent() method, you run into the risk of creating an infinite loop. Here you have called it twice once in paintComponent and again in clear method which is called by paintComponent.