Question

Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent()...

Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent() method to check when the ball has hit the edge of the window.

  1. When the ball reaches an edge, you will need to reverse the corresponding delta direction and position the ball back in bounds.

  2. Make sure that your solution still works when you resize the window. Your bounds checking should not depend on a specific window size

This is the java code that I'm currently working with:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 * Animated program with a ball bouncing off the program boundaries
 * @author CS121 Instructors
 * @author mvail
 * @author yourname
 */
@SuppressWarnings("serial")
public class BouncyBall extends JPanel
{
        private final int INIT_WIDTH = 600;
        private final int INIT_HEIGHT = 400;
        private final int DELAY = 60;       // milliseconds between Timer events

        private Random random;              // random number generator
        private Color color;                // initial ball color

        private int x, y;                   // ball anchor point coordinates
        private int xDelta, yDelta;         // change in x and y from one step to the next

        private int radius = 10;            // ball radius

        /**
         * Draws a filled bouncy ball that stays within the bounds of the screen.
         *
         * @param g Graphics context
         */
        public void paintComponent(Graphics g)
        {
                int width = getWidth();
                int height = getHeight();

                // Clear canvas
                g.setColor(getBackground());
                g.fillRect(0, 0, width, height);

                // Calculate new x anchor point value
                x += xDelta;
                // TODO: Add conditional statements to keep ball in bounds
                //       in the x axis (e.g. left and right edges)


                // Calculate new y anchor point value
                y += yDelta;
                // TODO: Add conditional statements to keep ball in bounds
                //       in the y axis (e.g. top and bottom edges)


                
                // Paint the ball at the calculated anchor point
                g.setColor(color);
                g.fillOval(x-radius, y-radius, 2*radius, 2*radius);

                // Makes the animation smoother
                Toolkit.getDefaultToolkit().sync();
        }

        /**
         * Constructor for the display panel initializes necessary variables.
         * Only called once, when the program first begins.
         * This method also sets up a Timer that will call paintComponent() 
         * with frequency specified by the DELAY constant.
         */
        public BouncyBall()
        {
                setPreferredSize(new Dimension(INIT_WIDTH, INIT_HEIGHT));
                setDoubleBuffered(true);
                setBackground(Color.black);

                 // Instantiate instance variable for reuse in paintComponent()
                random = new Random();

                // Initialize ball color
                // TODO: replace with random starting color.
                color = Color.RED;

                // Initialize ball anchor point within panel bounds
                // TODO: replace centered starting point with a random
                // position anywhere in-bounds - the ball should never
                // extend out of bounds, so you'll need to take RADIUS
                // into account. Use INIT_WIDTH and INIT_HEIGHT as the
                // screen width and height.
                x = INIT_WIDTH/2;
                y = INIT_HEIGHT/2;

                // Initialize deltas for x and y
                xDelta = 5;
                yDelta = 5;

                //Start the animation - DO NOT REMOVE
                startAnimation();
        }

        /**
         * Create an animation thread that runs periodically. DO NOT MODIFY.
         */
        private void startAnimation()
        {
                ActionListener taskPerformer = new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                                repaint();
                        }
                };
                new Timer(DELAY, taskPerformer).start();
        }

        /**
         * Starting point for the BouncyBall program. DO NOT MODIFY.
         * @param args unused
         */
        public static void main (String[] args)
        {
                JFrame frame = new JFrame ("Bouncy Ball");
                frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(new BouncyBall());
                frame.pack();
                frame.setVisible(true);
        }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Random;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.Timer;

/**

* Animated program with a ball bouncing off the program boundaries

* @author CS121 Instructors

* @author mvail

* @author yourname

*/

@SuppressWarnings("serial")

public class BouncyBall extends JPanel{

       private final int INIT_WIDTH = 600;

     private final int INIT_HEIGHT = 400;

     private final int DELAY = 60;       // milliseconds between Timer events

     private Random random;              // random number generator

     private Color color;                // initial ball color

     private int x, y;                   // ball anchor point coordinates

     private int xDelta, yDelta;         // change in x and y from one step to the next

     private int radius = 10;            // ball radius

     /**

      * Draws a filled bouncy ball that stays within the bounds of the screen.

      *

      * @param g Graphics context

      */

    

     public void paintComponent(Graphics g)

     {

             int width = getWidth();

             int height = getHeight();

             // Clear canvas

             g.setColor(getBackground());

             g.fillRect(0, 0, width, height);

             // Calculate new x anchor point value

             x += xDelta;

             // TODO: Add conditional statements to keep ball in bounds

             //       in the x axis (e.g. left and right edges)

            

             // check if the left-most coordinate of the ball is beyond the left edge

             // or right most coordinate of the ball is beyond the right edge, then reverse xDelta

             if((x-radius) < 0 || (x+radius) > width)

            x -= xDelta;

             // Calculate new y anchor point value

             y += yDelta;

             // TODO: Add conditional statements to keep ball in bounds

             //       in the y axis (e.g. top and bottom edges)

            

             //check if the top-most coordinate of the ball is beyond the top edge

             // or bottom most coordinate of the ball is beyond the bottom edge, then reverse yDelta

             if((y-radius) < 0 || (y+radius) > height)

            y -= yDelta;

            

             // Paint the ball at the calculated anchor point

             g.setColor(color);

             g.fillOval(x-radius, y-radius, 2*radius, 2*radius);

             // Makes the animation smoother

             Toolkit.getDefaultToolkit().sync();

     }

     /**

      * Constructor for the display panel initializes necessary variables.

      * Only called once, when the program first begins.

      * This method also sets up a Timer that will call paintComponent()

      * with frequency specified by the DELAY constant.

      */

     public BouncyBall()

     {

             setPreferredSize(new Dimension(INIT_WIDTH, INIT_HEIGHT));

             setDoubleBuffered(true);

             setBackground(Color.black);

              // Instantiate instance variable for reuse in paintComponent()

             random = new Random();

             // Initialize ball color

             // TODO: replace with random starting color.

            

             // randomly select the ball color

             color = new Color(random.nextFloat(),random.nextFloat(),random.nextFloat());

             //color = Color.RED;

             // Initialize ball anchor point within panel bounds

             // TODO: replace centered starting point with a random

             // position anywhere in-bounds - the ball should never

             // extend out of bounds, so you'll need to take RADIUS

             // into account. Use INIT_WIDTH and INIT_HEIGHT as the

             // screen width and height.

             

             // randomly select the starting point of the ball

             // the ball must be within the bounds i.e x = [10,590] and y = [10,390] since radius = 10

             x = random.nextInt(INIT_WIDTH-(2*radius)+1)+radius;

             y = random.nextInt(INIT_HEIGHT-(2*radius)+1)+radius;

             //x = INIT_WIDTH/2;

             //y = INIT_HEIGHT/2;

             // Initialize deltas for x and y

             xDelta = 5;

             yDelta = 5;

             //Start the animation - DO NOT REMOVE

             startAnimation();

     }

     /**

      * Create an animation thread that runs periodically. DO NOT MODIFY.

      */

     private void startAnimation()

     {

             ActionListener taskPerformer = new ActionListener() {

                     public void actionPerformed(ActionEvent evt) {

                             repaint();

                     }

             };

             new Timer(DELAY, taskPerformer).start();

     }

     /**

      * Starting point for the BouncyBall program. DO NOT MODIFY.

      * @param args unused

      */

     public static void main (String[] args)

     {

             JFrame frame = new JFrame ("Bouncy Ball");

             frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

             frame.getContentPane().add(new BouncyBall());

             frame.pack();

             frame.setVisible(true);

     }

      

}

//end of program

Output:

Add a comment
Know the answer?
Add Answer to:
Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent()...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Program The goal of this assignment is to develop an event-based game. You are going...

    Java Program The goal of this assignment is to develop an event-based game. You are going to develop a Pong Game. The game board is a rectangle with a ball bouncing around. On the right wall, you will have a rectangular paddle (1/3 of the wall height). The paddle moves with up and down arrows. Next to the game board, there will be a score board. It will show the count of goals, and count of hits to the paddle....

  • Fix the todo in ball.java Ball.java package hw3; import java.awt.Color; import java.awt.Point; import edu.princeton.cs.algs4.StdDraw; /** *...

    Fix the todo in ball.java Ball.java package hw3; import java.awt.Color; import java.awt.Point; import edu.princeton.cs.algs4.StdDraw; /** * A class that models a bounding ball */ public class Ball {    // Minimum and maximum x and y values for the screen    private static double minX;    private static double minY;    private static double maxX;    private static double maxY;    private Point center;    private double radius;    // Every time the ball moves, its x position changes by...

  • Modify the NervousShapes program so that it displays equilateral triangles as well as circles and rectangles....

    Modify the NervousShapes program so that it displays equilateral triangles as well as circles and rectangles. You will need to define a Triangle class containing a single instance variable, representing the length of one of the triangle’s sides. Have the program create circles, rectangles, and triangles with equal probability. Circle and Rectangle is done, please comment on your methods so i can understand */ package NervousShapes; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; public class...

  • "Polygon Drawer Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked." import...

    "Polygon Drawer Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked." import java.awt.*; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.applet.*; public class PolygonDrawer extends Applet implements MouseListener{ //Declares variables    private int[] X, Y;    private int ptCT;    private final static Color polygonColor = Color.BLUE; //Color stuff    public void init() {        setBackground(Color.BLACK);        addMouseListener(this);        X = new int [450];        Y =...

  • Need help writing Java code for this question. CircleFrame class is provided below. what happen after...

    Need help writing Java code for this question. CircleFrame class is provided below. what happen after u add the code and follow the requirement? It would be nice to be able to directly tell the model to go into wait mode in the same way that the model's notify method is called. (i.e. notify is called directly on the model, whereas wait is called indirectly through the suspended attribute.) Try altering the the actionPerformed method of the SliderListener innner class...

  • JavaFX programming (Not Javascript) Using the code from BallPane.java and BounceBallControl.java create a "Pong for One"...

    JavaFX programming (Not Javascript) Using the code from BallPane.java and BounceBallControl.java create a "Pong for One" game - a rectangular paddle moves back and forth via mouse drag along the bottom of the pane; the bottom of the paddle should be about 1/2 the diameter of the ball off the bottom. If the ball connects with the paddle, then it bounces at a 90 degree angle back into the pane space. If the ball misses the paddle, then the score...

  • Hi! I'm working on building a GUI that makes cars race across the screen. So far...

    Hi! I'm working on building a GUI that makes cars race across the screen. So far my code produces three cars, and they each show up without error, but do not move across the screen. Can someone point me in the right direction? Thank you! CarComponent.java package p5; import java.awt.*; import java.util.*; import javax.swing.*; @SuppressWarnings("serial") public class CarComponent extends JComponent { private ArrayList<Car> cars; public CarComponent() { cars = new ArrayList<Car>(); } public void add(Car car) { cars.add(car); } public...

  • Stick to the template which is provided on below and just change the //TODO part, please....

    Stick to the template which is provided on below and just change the //TODO part, please. Template Lab13.java package lab13; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.IOException; public class Lab13 {    public static void main (String[] args) {        JFrame frame = new SmileyFrame();        frame.add(new SmileyPanel());        frame.setVisible(true);    } } class SmileyFrame extends JFrame {    private static final long serialVersionUID = 7613378514394599117L;    private static final int WIDTH = 400;...

  • // ====== FILE: Point.java ========= // package hw3; /** * A class to that models a...

    // ====== FILE: Point.java ========= // package hw3; /** * A class to that models a 2D point. */ public class Point { private double x; private double y; /** * Construct the point (<code>x</code>, <code>y</code>). * @param x the <code>Point</code>'s x coordinate * @param y the <code>Point</code>'s y coordinate */ public Point(double x, double y) { this.x = x; this.y = y; } /** * Move the point to (<code>newX</code>, <code>newY</code>). * @param newX the new x coordinate for...

  • I have to create a java graphics program which will draw 10 rectangles and 10 ellipses...

    I have to create a java graphics program which will draw 10 rectangles and 10 ellipses on the screen. These shapes are to be stored in an arrayList. I have to do this using 6 different class files. I am not sure whether I successfully created an ellipse in the Oval Class & also need help completing the print Class. I need someone to check whether my Oval Class is correct (it successfully creates an ellipse with x, y, width,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT