[Solved] Casting Error with Graphics2D

Hey there,

I’ve tried to create a extended Graphics2D Class, but it won’t work.
Here is a piece of my code:


public abstract class SimpleGraphics2D extends Graphics2D {
    // Currently, here is nothing.
}

If I try to cast a Graphics or Graphics2D Object to a SimpleGraphics2D Object I get this error:

[quote]Exception in thread “Thread-3” java.lang.ClassCastException: sun.java2d.SunGraphics2D cannot be cast to de.mdstv.simple2d.SimpleGraphics2D
at de.mdstv.simple2d.GamePanel.getSimpleGraphics2D(GamePanel.java:60)
at de.mdstv.simple2d.SimpleGame.gameLoop(SimpleGame.java:154)
at de.mdstv.simple2d.SimpleGame.access$0(SimpleGame.java:108)
at de.mdstv.simple2d.SimpleGame$1.run(SimpleGame.java:83)
[/quote]
Anyone knows a solution? :-\

King Regards
Morph

You can’t cast it to something that it is not; Java2D gives you a Graphics2D, so that’s what you’ve got to use.

What you need to do is wrap it and extend the wrapper.


public class SimpleGraphics2D {
	Graphics2D g2d;
	
	SimpleGraphics2D(Graphics2D g2d) {
		this.g2d = g2d;
	}
	
	// Now delegate any methods you want to g2d
}
...
public void paint(Graphics g) {
	SimpleGraphics2D sg2d = new SimpleGraphics2D((Graphics2D) g);
...
}

Cas :slight_smile:

Perfect!
Thank you :slight_smile:

King regards
Morph