Ewen
Ewen

Reputation: 1028

Java - paintComponents on a JPanel not working

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. :)

Upvotes: 3

Views: 1816

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168815

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 paintComponent method (not paintComponents do not override that).

Other tips

  • Remember to call super.paintComponent(g);. This is important to ensure that borders and padding etc. are accounted for.
  • Swap null for this. Every JComponent is an ImageObserver.

Upvotes: 7

please note that JFrame is NOT a JComponent! In fact, the paintComponents(Graphics) method is NEVER called. A fix would be subclassing JPanel and adding your subclassed panel to the frame as the content pane. In the panel override the paintComponents(Graphics) method.

Upvotes: 2

Related Questions