Sign in to follow this  

How Is This Side Effect Happening ?

Recommended Posts

RLS0812    3043

I have run into an interesting side effect in my code. It seems like turning on RenderingHints for my Graphics g1 object also is affecting my Graphics g object.


 As it is written, the Graphics g object should not be anti-aliased, only g1 object .... am I not "getting" something here ?


public void paint(Graphics g){
     Graphics2D g1 = (Graphics2D) g;
     RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     g.fillRect(0, 0, WIDTH + 20, HEIGHT + 20);
     g.drawString("\u263a \u263b",20,20);
Edited by Shippou

Share this post

Link to post
Share on other sites
TheChubu    9446

lol Yeah, you're not getting Java :D Its the same object dude, you're just casting it to another type.


Its common to cast the incoming Graphics object to Graphics2D inside the method to do more interesting stuff with it (drawImage for example).

Share this post

Link to post
Share on other sites
Moe091    594

yah what they are saying, you are just creating a new reference to the g object and calling it g1, your also casting it to a graphics2d so that reference treats it as a graphics2d object, which means you can use graphics2d methods on the object but it is still the same object your are performing the methods on.


If you really want to create a new object I believe there is a graphics.create() method that returns a copy.

Graphics2D g1 = (Graphics2D) g.create();

That should give you the desired effects I believe, now g1 is a COPY of the g object and it is still being cast to a Graphics2D

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this