tags:

views:

175

answers:

5

More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}

Or am I missing the point here? Is there a better way to handle this in general?

+6  A: 
Graphics2D g2 = (Graphics2D)g;

There is no need to be fancy about it.

You will always receive a G2D in the paint method.

I even like to call the Graphics parameter g2 and then cast to a Graphics2D named g to make using it simpler.

jjnguy
So you always receive one? Why are the arguments in the declaration "Graphics g" and there is no "Graphics2D g" alternative to override? Internally is a Graphics2D object being cast to a Graphics object for backward compatibility and then you're able to restore it to a Graphics2D if you need to?
spligak
You are being given a Graphics object for some historical reason that I have grown to not care about. I just always do the cast if I need G2D methods.
jjnguy
You might want to use g as the Graphics2D variable as it is going to be used throughout the code. You could also have a general component and forward to a renderer using an interface that uses Graphics2D instead of Graphics for parameters.
Tom Hawtin - tackline
A: 
Graphics2D g2 = Graphics2D.class.cast(g);
Pierre
Why would you do that?
jjnguy
A: 

As far as I know, you can't do much in this situation. You can validate that you actually got a Graphics2D object before casting. But, as far as I know, you can get anything else anyway.

Untrots
A: 

Personally I like

Graphics2D g2 = g as Graphics2D;
if (g2 == null)
//do stuff

But as said before, no reason to make it anymore complicated than it is :P

cwap
Can you use 'as' in java?
jjnguy
I didn't think so.
jjnguy
Oh, it's java .. My bad. I was sleepy :O
cwap
A: 

Its not directly relevant, but in Scala they recognised this "unpleasantness" - and encourage you to use pattern matching to deal with the correct class instead of a cast:

g match { 
     case Graphics2D(g2d) => //code goes here !
     case _ => Nothing //or throw exception etc
}

They actively discourage casts (there is no special cast syntax, only a method).

Not entirely relevant to you, but thought its worth noting that others are troubled by what troubles you ;)

Michael Neale