I am trying to draw multiple car objects onto the same window but it appears that they are overwriting each other.
Here is my overridden paintComponent method in the Car class
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(wheelColor);
g2.fill(leftWheel);
g2.fill(rightWheel);
g2.setColor(bodyColor);
g2.fill(body);
g2.fill(cab);
}
And in my Viewer Class:
JFrame f = new JFrame();
initializeFrame(f);
Car x = new Car(100, 100);
Car y = new Car(300, 300);
f.add(x);
f.add(y);
Although the coordinates seem to be different, only the last car is being drawn.
Any suggestions? Thanks
The default layout manager for a JFrame is a BorderLayout. So by default you are adding all your components to the CENTER of the BorderLayout. However, you can only ever add one component to the CENTER so only the last Car is displayed.
Change the Layout Manager to a FlowLayout to see the difference.
Or, it looks like you are trying to paint the Cars in random positions, in which case you should use a "null" layout. Then you will be responsible for setting the size/location of each of the Car components.
What you want to do is use a data structure of
Car
objects and loop through them in thepaintComonent
method. Something likeThe
drawCar
method would come from yourCar
classSee more examples here and here and here and here and here and here.
UPDATE
Here is a simple example use some "Ferraris" I whipped up, also using some animation, but with the same basic points I have above.