import java.awt.*; // Needed for window and graphics (explained in COMP1406) import javax.swing.*; // Needed for window and graphics (explained in COMP1406) // This application simulates balls bouncing in a window public class BallSimulation { // This variable stores the panel that displays the balls // (This is a topic discussed in COMP1406 course) public static BallPanel ballPanel; public static void startSimulation(Ball[] balls) { while(true) { for (int i=0; i= BallPanel.WIDTH) || (balls[i].x - balls[i].radius <= 0)) balls[i].direction = (float)(Math.PI - balls[i].direction); if ((balls[i].y + balls[i].radius >= BallPanel.HEIGHT) || (balls[i].y - balls[i].radius <= 0)) balls[i].direction = -balls[i].direction; } ballPanel.repaint(); try{ Thread.sleep(10); } catch(Exception e){}; } } // Create a window with a BallPanel, add 3 balls and start the simulation public static void main(String args[]) { Ball[] balls = new Ball[3]; balls[0] = new Ball(); balls[0].x = 100; balls[0].y = 100; balls[0].direction = (float)(Math.random()*2*Math.PI); balls[0].speed = 15; balls[0].radius = 20; balls[1] = new Ball(); balls[1].x = 400; balls[1].y = 300; balls[1].direction = (float)(Math.random()*2*Math.PI); balls[1].speed = 10; balls[1].radius = 30; balls[2] = new Ball(); balls[2].x = 600; balls[2].y = 400; balls[2].direction = (float)(Math.random()*2*Math.PI); balls[2].speed = 5; balls[2].radius = 50; JFrame frame = new JFrame("Ball Simulation"); frame.add(ballPanel = new BallPanel(balls)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); // Makes size according to panel's preference frame.setVisible(true); startSimulation(balls); } }