First of, we need a JFrame object.
Then, we create an object of a class extending the JComponent class and inserting the appropriate instructions in the paintComponent(Graphics g)
method, where g is actually a Graphics2D
object and attach this to the JFrame object.
Now, what I've been taught is that to draw a rectangle, I do:
class RectangleComponent extends JComponent {}
Now, to draw a circle, I do:
class CircleComponent extends JComponent{}
and so on,
However, I want to have one common class that can draw multiple shapes.
I did the following:
class Component extends JComponent {
Shape shape;
public Component(Shape shape) {
this.shape = shape;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.draw(this.shape);
}
}
In the main, when I get an instruction to draw a rectangle, I do:
Shape currentShape = new Rectangle(args);
Component component = new Component(currentShape);
frame.add(component);
Immediately following this, I get an instruction to draw a circle and I do:
Shape currentShape = new Ellipse2D.Double(args);
Component component = new Component(currentShape);
frame.add(component);
Being a rookie that I am, this is where I get lost. I think this makes the circle overwrite the rectangle. But that's not my intention. What should I do to make them both appear together? I think I should draw them both on the same Component object. But how do I accommodate it in my current implementation?