Search code examples
javaswingcanvasjpanelpaintcomponent

Where to place the drawing code in a JPanel used as canvas


I've a JPanel where I'm drawing with the mouse events and after resizing, or minimizing-restoring it, it doesnt display what has to be drawn, despite a "degub" println shows me the function is being called, but for some reason, it reamains blank

I thought I should have added my drawing function in the paintComponent function but it seems not to be working right, so what I'm doing wrong or where should I place that drawElements() call?

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    drawElements();
}
void drawElements() {
    Graphics2D g = (Graphics2D)this.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
            RenderingHints.VALUE_ANTIALIAS_ON);

    for (Element el : elements) {
        el.draw(g);
    }
}

Solution

  • Pass the graphics object to the drawElements method.

    (Right answer provided by @rafalopez79)