Hey Guys,
I am creating a program which creates two balls (each with their own runnables which control them). This is the important code from the file:
public BallsFrame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); addBall(150,50); addBall(200,100); // add two balls to pane } // addBall to panel at specified coordinates (x,y) public void addBall(int x, int y) { // create coloured ball and add to panel BallComponent ball = new BallComponent(x, y); add(ball); // create a runnable to control ball Runnable r = new ColoredBallRunnable(ball); Thread t = new Thread(r); System.out.println("addBall t started..."); t.start(); System.out.println("addBall t finished..."); }
The ControlBallRunnable is here:
To explain this: when the runnable is created, it creates a timer which changes the colour of the ball (using method ball.animate() ) every 1000ms i.e. every second.public class ColoredBallRunnable implements Runnable { BallComponent ball; ColoredBallPanel cbPanel; public ColoredBallRunnable(BallComponent ball){//, ColoredBallPanel cbPanel){ this.ball = ball; this.cbPanel = cbPanel; } public void run() { class TimerListener implements ActionListener { public void actionPerformed(ActionEvent event) { ball.animate(); } } TimerListener listener = new TimerListener(); Timer t = new Timer(1000, listener); t.start(); } }
Now my problem is this code partially works, it successfully creates one ball (the first time addBall() is called).
It refuses to create more than one ball.
Now, ive researched this problem for the last couple of days and cant seem to find a solution. Please help me. If you need any clarifications, extra code etc, i will provide it.