CMPE 261 - Lab worksheet - Week 7

Problem 1: Bouncing ball

The following program will display a ball object on the screen. In this problem you are asked to implement the ball class only so that in each call to its move function, the ball will move, and if necessary bounce from the walls of the window:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;        
    import java.awt.geom.*;

    class Ball {
        double radius;
        Color color=Color.blue;
        double posX,posY;
        double velocityX, velocityY;
        Ball(double x,double y,double vx,double vy,double radius) {
            posX=x;
            posY=y;
            velocityX=vx;
            velocityY=vy;
            this.radius=radius;
        }
        void move() {
            System.out.println("please implement me!");
        }
    }
    class DrawingPanel extends JPanel {
        Ball ball;
        DrawingPanel() {
            super();
            setPreferredSize(new Dimension(400,400));
            this.ball=new Ball (200,200,2,3,40);
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(ball.color);
            ((Graphics2D)g).fill(new Ellipse2D.Double(ball.posX-ball.radius,ball.posY-ball.radius,ball.radius,ball.radius));
        }
        void moveBall() {
            ball.move();
        }
    }

    class BallGUI extends JFrame{
        DrawingPanel panel;
        BallGUI(String title) {
            super(title);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLayout(new FlowLayout());
            setPreferredSize(new Dimension(400,500));        

            panel = new DrawingPanel();
            add(panel);
            JButton closeButton=new JButton("Close");
            add(closeButton);

            closeButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    System.exit(0);
                }
            });

            //pack the frame, ready to display
            pack();
        }
        void moveBall() {
            panel.moveBall();
        }
        public static void main(String[] args) {
            BallGUI mainFrame = new BallGUI("Balls");
            mainFrame.setVisible(true);
            try {
              while(true) {
                Thread.sleep(200);
                mainFrame.moveBall();
                mainFrame.repaint();
              }
            } catch(Exception e) {
                System.out.println(e);
            }
        }
    }

Problem 2: multiple balls

Improve you code such that the panel will display 10 balls of varying size and color (you may use Random to create them, if you wish). All the balls will bounce from walls, but you may ignore ball collisions.