import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * World.java * * A class demonstrating Swing 2D graphics using a bouncing * ball. See Ball.java. * * @author Jeff Ondich * * @version 1.0.0 * date: 02.09.2010 */ public class World extends JFrame { private JPanel panel; private Ball ball; /** * A bouncing ball demonstration. */ public static void main(String[] args) { // Initialize the frame window and the bouncing ball object. Color backgroundColor = Color.black; int worldWidth = 600; int worldHeight = 400; World world = new World(worldWidth, worldHeight, backgroundColor); world.setBall(new Ball(worldWidth / 2, worldHeight / 2, 40)); world.getBall().setColor(Color.red); world.getBall().setVelocity(10, 10); world.setVisible(true); world.repaint(); // Run the animation. Graphics g = world.getPanel().getGraphics(); Ball ball = world.getBall(); while( true ) { try { Thread.sleep(100); } catch (Exception e) { } // Erase, bounce if necessary, step, and redraw. ball.erase(g, backgroundColor); int vx = ball.getVelocityX(); int vy = ball.getVelocityY(); int x = ball.getX(); int y = ball.getY(); int r = ball.getRadius(); if( x + r > worldWidth || x - r < 0 ) { ball.setVelocity(-vx, vy); } if( y + r > worldHeight || y - r < 0 ) { ball.setVelocity(vx, -vy); } ball.step(); world.getBall().draw(g); } } /** * Default constructor. */ public World() { this(500, 300, Color.green); } /** * Initialize a World object with the specified width, height * and color. Create a drawing pane to fill the World, and * set a listener to shut down the program when the close-box * is clicked. * * @param width The width in pixels of the desired frame window. * @param height The height in pixels of the desired frame window. * @param backroundColor The color of the frame window's background. */ public World(int width, int height, Color backgroundColor) { this.setTitle("The World"); // Fill this frame window with the pane in which drawing will take place. panel = new JPanel(); panel.setBackground(backgroundColor); panel.setPreferredSize(new Dimension(width, height)); panel.setVisible(true); this.setContentPane(panel); this.pack(); // This will make the close-box on the frame window shut down the program. this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false); System.exit(0); } }); } /* ========== World accessors ============ */ public void setBall(Ball b) { ball = b; } public Ball getBall() { return ball; } public JPanel getPanel() { return panel; } }