How would I iterate through a list of objects to paint their draw() methods? If I have it set up correctly how do I implement this correctly?
Class I'd like to draw onto:
public class Window extends JPanel implements IObserver, ActionListener{ private Timer timer = new Timer(5, this); public Window(){ super.setBorder(BorderFactory.createTitledBorder("Window:")); timer.start(); } public void update(IObservable o, Object arg){ GameWorldProxy gwp = (GameWorldProxy) o; Iterator gameObjects = gwp.getCollection().getIterator(); while(gameObjects.hasNext()){ GameObject gameObj = (GameObject) gameObjects.getNext(); System.out.println(gameObj); } } public void paintComponent(Graphics g){ super.paintComponent(g); } public void actionPerformed(ActionEvent e){ repaint(); } }
Car class:
public class Car extends MoveableObject implements ISteerable, IDrawable{ public void draw(Graphics g, int x, int y) { g.setColor(Color.RED); g.fillRect(x, y, 25, 10); } }
So for example, I have a few different classes other than the Car class. It has a draw() method in there and the GameObject class extends from Car From my understanding I should also have a draw() method in GameObject. Say there's 2 listing of Cars under the gameObj, how would I draw them both? I'm not sure I quite understand how to iterate through the list to draw it on the panel.
The solution as intimated in the comments is to iterate through your list of Cars in the paintComponent method, and draw them there using the Graphics object that the JVM has given you. Use a for loop in that method, and in the loop call each Car's drawing method. And as mentioned, a Swing Timer should never be started within a painting method, nor should any of the object's behaviors or states be changed, other than to draw them and that's it.
No comments:
Post a Comment