Big_Bad_E
Big_Bad_E

Reputation: 847

Java drawing shape to bufferedImage from outside paintComponent()?

This has probably been asked a bit but I need help with drawing shapes. So I have my Draw class which extends JPanel.

I want to be able to draw an oval from outside the paintComponent(); method. So to load all my images I try to draw the shapes to a BufferedImage. But I don't have a proper Graphics object.

So my question is: How would I get a proper Graphics object to draw to my JPanel with, or how would I draw inside the paintComponent method and be able to call it from another class?

Upvotes: 0

Views: 901

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

You get a Graphics object from the BufferedImage via getGraphics() or a Graphics2D object via createGraphics(). You then draw the image within paintComponent by calling drawImage on its Graphics parameter. Do dispose the BufferedImage's Graphics object when you're done using it since you created it. Do not dispose the Graphics object passed into paintComponent since the JVM made it.

Upvotes: 3

MadProgrammer
MadProgrammer

Reputation: 347332

How would I get a proper Graphics object to draw to my JPanel with, or how would I draw inside the paintComponent method and be able to call it from another class?

You don't. You should never call any paint method manually. There's a lot going on in the background which you don't control when a component is painted this way.

If you want to "print" a component, then you should be using paintAll.

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
componentToBePrinted.printAll(g2d);
g2d.dispose();

An alternative would be to use a BufferedImage and paint to it instead...

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.BLACK);
g2d.draw(new Rectangle2D.Double(10, 10, 80, 80));
g2d.draw(new Ellipse2D.Double(10, 10, 80, 80));
g2d.dispose();

You could then have a component paint it using Graphics#drawImage

Upvotes: 2

Related Questions