views:

73

answers:

1

I've created a JPanel canvas that holds all graphics; namely JLabel. To get animated sprites to work you have to over ride the paintComponent of the extended JLabel class. I've successfully implemented animated sprites this way.

Is it bad practice to have a Graphics2D canvas and then have multiple 'images' in their own Graphics2D?

+2  A: 

I don't think it will be too much heavyweight since the Graphics2D of your JPanel should be the same one that is passed to the JLabel but with different bounds and offsets.

What I mean is that Swing doesn't allocate a new graphics context on which you can display for every element inside a hierarchy of objects but it uses the same with different capabilities. This doesn't mean that panel.getGraphics() == label.getGraphics() but neither they are completely different obects.

In any case, if you need to do much animated work I would suggest you to have your own sprite class

class Sprite
{
  Point2D position;
  Rectangle2D size;
  float rotation;
}

and handle everything at the same paintComponent level. Or at least I've always did that way since Java2D is not like CoreAnimation that is made to be used on a per-layer basis for moving/animated content.

Jack