CodeRed
CodeRed

Reputation: 63

Java: How to copy a graphics object and reuse it?

I thought the create() function of graphics object creates a new copy of the current graphics object

this was my code

Graphics temp;
temp = g.create();
temp.drawString("hello world",100,100);
g.fillRect(200,200,50,50);

Now my understanding was that since temp is now a copy of the g, any change on temp would not be reflected on g. So my output should have been just a rectangle due to the fillRect function. But I am getting both the string and the rectangle on my paint output. Why is this happening and how to stop it?

Upvotes: 2

Views: 5430

Answers (3)

Wayne
Wayne

Reputation: 343

Graphics.create gives you a full or specified section of the Graphics object that generated it - it is not a new Graphics object.

If you wish to draw to a graphics object (and reuse said object) I would suggest using the BufferedImage derivative, OffscreenImage and, from there, draw to the OffscreenImage.getGraphics

Upvotes: 0

JbaocPeeps
JbaocPeeps

Reputation: 11

I am a beginner in java, but, after looking into your code i see that you have put g.create(); (i'm not very sure but) this could possibly mean that everything declare with g. would be affected. I suggest doing so:

Graphics2D g2d = (Graphics2D) g;
Graphics temp;
temp = g2d.create();
temp.drawString("hello world",100,100);
g.fillRect(200,200,50,50);

hope it worked

Upvotes: 1

H3XXX
H3XXX

Reputation: 647

Can't you just make a class for the object, for example TextString and Box, and make them have a paint method like so:

public void paint(Graphics g){
    g.setColor(Color.RED);
    g.fillRect(50, 50, 100, 100);
}

And then wherever you are drawing the objects, call box.paint(g); or whatever you called your object.

This way you can change the properties of the objects and draw them independently anytime you want without affecting the other objects.

Upvotes: 0

Related Questions