I created a class that extends a JFrame and added a JPanel inside it, but the paintComponents() method doesn’t draw anything on the JPanel. Heres the code for the paintComponents(), I chose to use double image buffering.
public void paintComponents(Graphics graphics) {
panel.paintComponents(graphics);
bufferedImage = createImage(sizeX, sizeY);
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
for (ImageData myImage : imageData) {
g.drawImage(myImage.getImage(), myImage.getX(), myImage.getY(), null);
}
graphics.drawImage(bufferedImage, 0, 0, null);
}
Is there anything wrong with this? Btw, I tried paint() and it worked but I dont think it’s the proper way to do this.
Thanks for your time. 🙂
Do not extend a top level component such as a
JFrame. Instead keep an instance of a frame, and add a panel to that. All custom painting or addition of components is done in the panel.When doing custom painting in a panel, do it in the
paintComponentmethod (notpaintComponentsdo not override that).Other tips
super.paintComponent(g);. This is important to ensure that borders and padding etc. are accounted for.nullforthis. EveryJComponentis anImageObserver.