Search code examples
javaswinggraphicsstandardsgraphics2d

Java best-practices/standards drawing practices


What is the best practice or standard for drawing graphics in java? I have my Jframe with a Jpanel and a Class(foo) which contains a Polygon(shape). If I want to display the classes shape should I call foo.draw(pass it the graphics2d and a few other things) and have it draw itself (which I think would be encapsulation? which I believe is preferred?) or do all the drawing within my drawScreen() method?

Thank you


Solution

  • If the Foo should never overlap with any other graphics, e.g. it is a Label or a Button, then it should definitely draw itself. I suggest that it extend JComponent, implement paintComponent(), and be added using a LayoutManager etc. etc.

    If the Foo can overlap with other graphics (say, it's some space game and the polygon is a quickly moving asteroid heading towards earth) then things get trickier. I still think it best if the Foo knows how to draw itself to a Graphics, but you might not want to extend JComponent.

    option 1: extend JComponent and implement paintComponent, but note in the javadocs that this is not a "real" JComponent and that it never gets added using a LayoutManager. You can even change addNotify() to throw an exception to prevent this.

    Option 2: have the Foo implement Icon - a nice little interface for lightweight drawings.

    This still begs the question, something else needs to tell it to draw itself. So something needs to keep a list of these JComponents or Icons and tell them to draw...