Hi, I am not understanding how to draw my custom components onto a panel. My teacher is asking for an abstract class, Shape, which cannot extend or implement anything. Then I have two subclasses, Circle and Square, that extend Shape (so they cannot extend anything else like JComponent). Finally I have a class, Draw, that creates a main window and adds three buttons. One button adds Circle objects, one button adds Square objects, and the other button changes the colors of the objects. Currently, when I click "Add Circle," I get runtime exceptions. Can anyone help me understand why? Here's my source:
Sorry there's so much code... I have a feeling it has something to do with the way I'm handling the event in the actionPerformed method (right at the bottom of Draw.java). Thanks for any help!
It would have helped if you included the stack trace.
The problem is with private Shape shape; - you never initialize it. Where is your line that says "shap = new Shape[...]"?
If you don't want to limit the number of shapes to 5, you may want to consider using a List:
It has its own counter for the number of elements to (shapes.size()), so numOfShapes becomes obsolete.
Edit: after adding that line your code still does not work. That's because you're not overriding paintComponent in Draw - JFrame has no such method. You need paint instead; also don't forget to call super.paint(g); first.
Also, don't make x and y static. That way all your shapes will have the same coordinates.
Darryl Burke wrote:The correct way to do custom painting in Swing is to override paintComponents of a JComponent (or any subclass of it).
Shouldn't that be paintComponent?
Bartek is right though, the best way is to use a JPanel subclass and extend its paintComponent method.
Yup, I had a typo in the worst possible place
Joined: Jul 11, 2006
Well this would make a lot more sense if my teacher would allow me to extend JComponent in the Shapes class. The Circle and Square class already extend a class, and multiple inheritance is not allowed, so what else can I do to make this work without "disobeying" specs? Is there an interface I can implement that makes my class a JComponent?
Thanks for the info on the shapes array, that's a dumb mistake on my part. Personally I'd rather program encryption algorithms thank program Swing components. But I know it's useful and I need to know it.
I'm sorry Rob, after reading your post again more carefully, it clicked in my head to change my paintComponents to paint(). I got something showing up on the screen, I think I can take it from here. Thanks a lot everyone!