1

I am trying to draw several things inside a JPanel. I am drawing shapes (works), and I also want to fill the JPanel with a picture. But paintComponent() only takes one argument. And this gets complicated when I have some extra code for drawing the shapes.

My paintComponent() method is currently like this:

public void paintComponent(Graphics g) {


    g2 = (Graphics2D) g;
    for (int i = 0; i < shapes.size(); i++) {
        Shape s = (Shape) shapes.get(i);
        if (s != null)
            g2.draw(s);
    }
}

I have searched around a lot and cannot find a way to do this.

Does anyone know how to do this, or maybe some workaround?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
geirmash
  • 136
  • 1
  • 1
  • 12
  • Have a look at this http://stackoverflow.com/questions/299495/java-swing-how-to-add-an-image-to-a-jpanel – Kakalokia Jan 28 '13 at 20:59
  • Do you have super.paintComponent(g)? – Coupon22 Jan 28 '13 at 21:12
  • Yes, i accidently left it out because i were removing some commenting. – geirmash Jan 28 '13 at 21:17
  • Thank you Ali Alamiri, but the real problem for me is that i pass in the image as a Graphics object. This gets complicated since the shapes drawn in paintComponent() is also passed in as Graphics objects. – geirmash Jan 28 '13 at 21:19
  • My bad. Ignore my last comment. I just added g2.drawImage(images[0], 0, 0, null); in paintComponent(). And repaint(); Thanks for answering guys! – geirmash Jan 28 '13 at 22:03

1 Answers1

1

Just like your approach to drawing shapes, you need to maintain a reference to the images you want to draw within the class and reference them in much the same way.

The following are all examples of drawing images within paintComponent, on a verity of topics

Nb - I may be misreading this, but you should never be calling paintComponent yourself. It is called on your behalf by the repaint engine within Swing

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366