How Is This Side Effect Happening ?

Started by
2 comments, last by Moe091 10 years, 1 month ago

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);
     g1.setRenderingHints(rh);
     g.setColor(Color.BLACK);
     g.fillRect(0, 0, WIDTH + 20, HEIGHT + 20);
     manager.draw(g);
     stage.draw(g);
     player.draw(g);
     g.setFont(font);
     g.drawString("\u263a \u263b",20,20);
     g.dispose();
     repaint();
	}

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Advertisement

Graphics2D g1 = (Graphics2D) g;

g1 IS g, since you are using a language which uses references for objects rather than copying them.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

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

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

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

This topic is closed to new replies.

Advertisement