Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: need to randomly change the size of programs balls

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default need to randomly change the size of programs balls

    I am starting to learn java at home and one of the tasks in the book is to create a program which randomly changes the size of balls which are bouncing off the screen, but all i seem to be able to do is get them to randomly start in different places not change size, can anyone help please?

    here is my code:

    import java.awt.*;
    import java.awt.geom.*;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Random;
    import java.util.ArrayList;
     
    /**
     * Class BallDemo - a short demonstration showing animation with the 
     * Canvas class. 
     *
     * @author Michael Kölling and David J. Barnes
     * @version 2011.07.31
     */
     
    public class BallDemo   
    {
        private Canvas myCanvas;
     
        /**
         * Create a BallDemo object. Creates a fresh canvas and makes it visible.
         */
        public BallDemo()
        {
            myCanvas = new Canvas("Ball Demo", 600, 500);
        }
     
            public void drawFrame() {
            int borderSize = 20;
            Dimension size = myCanvas.getSize();
            Rectangle r = new Rectangle(borderSize, borderSize, (int) size.getWidth() - 2*borderSize, (int) size.getHeight() - 2*borderSize);
            myCanvas.draw(r);
        }
     
     
        /**
         * Simulate two bouncing balls
         */
          public void bounce(int numberOfBalls)
        {
            int ground = 400;   // position of the ground line
            myCanvas.setVisible(true);
            // draw the ground
            myCanvas.drawLine(50, ground, 550, ground);
            // create and show the balls
            Random random = new Random();
            HashSet<BouncingBall> balls = new HashSet<BouncingBall>();
            for(int i=0; i<numberOfBalls; i++) {
                Dimension size = myCanvas.getSize();
                int x = random.nextInt((int) size.getWidth());            
                int y = random.nextInt((int) size.getHeight());
                BouncingBall ball = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
                balls.add(ball);
                ball.draw();
            }
     
     
            // make them bounce
            boolean finished =  false;
            while(!finished) {
                myCanvas.wait(50);           // small delay
                for(BouncingBall ball : balls) {
                    ball.move();
                    // stop once ball has travelled a certain distance on x axis
                    if(ball.getXPosition() >= 550 + 32*numberOfBalls) {
                        finished = true;
                    }
                }
            }
            for(BouncingBall ball : balls) {
                ball.erase();
            }
        }
    }
    Attached Files Attached Files


  2. #2
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default need to randomly change the size of programs balls

    I am starting to learn java at home and one of the tasks in the book is to create a program which randomly changes the size of balls which are bouncing off the screen, but all i seem to be able to do is get them to randomly start in different places not change size, can anyone help please?

    here is my code:bouncing balls.txt

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    Please paste the code in the forum wrapping it in code tags.
    If you don't understand my answer, don't ignore it, ask a question.

  4. The Following User Says Thank You to Norm For This Useful Post:

    jusjus7 (October 24th, 2013)

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  6. The Following User Says Thank You to Norm For This Useful Post:

    jusjus7 (October 24th, 2013)

  7. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need to randomly change the size of programs balls

    Can anybody please help? really stuck

  8. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    The posted code does not compile. There are several errors in it.
    You need to post all the classes the code uses.
    You should NOT use a name for a class that is the name of a standard java class: Canvas. It makes for much confusion. Give your class its own unique name.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need to randomly change the size of programs balls

    Ok sorry, below are my three classes. I have been able to get the balls to randomly bounce but not to randomly change size.

    import java.awt.*;
    import java.awt.geom.*;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Random;
    import java.util.ArrayList;
     
    /**
     * Class BallDemo - a short demonstration showing animation with the 
     * Canvas class. 
     *
     * @author Michael Kölling and David J. Barnes
     * @version 2011.07.31
     */
     
    public class BallDemo   
    {
        private Canvas myCanvas;
     
        /**
         * Create a BallDemo object. Creates a fresh canvas and makes it visible.
         */
        public BallDemo()
        {
            myCanvas = new Canvas("Ball Demo", 600, 500);
        }
     
            public void drawFrame() {
            int borderSize = 20;
            Dimension size = myCanvas.getSize();
            Rectangle r = new Rectangle(borderSize, borderSize, (int) size.getWidth() - 2*borderSize, (int) size.getHeight() - 2*borderSize);
            myCanvas.draw(r);
        }
     
     
        /**
         * Simulate two bouncing balls
         */
          public void bounce(int numberOfBalls)
        {
            int ground = 400;   // position of the ground line
            myCanvas.setVisible(true);
            // draw the ground
            myCanvas.drawLine(50, ground, 550, ground);
            // create and show the balls
            Random random = new Random();
            HashSet<BouncingBall> balls = new HashSet<BouncingBall>();
            for(int i=0; i<numberOfBalls; i++) {
                Dimension size = myCanvas.getSize();
                int x = random.nextInt((int) size.getWidth());            
                int y = random.nextInt((int) size.getHeight());
                BouncingBall ball = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
                balls.add(ball);
                ball.draw();
            }
     
     
            // make them bounce
            boolean finished =  false;
            while(!finished) {
                myCanvas.wait(50);           // small delay
                for(BouncingBall ball : balls) {
                    ball.move();
                    // stop once ball has travelled a certain distance on x axis
                    if(ball.getXPosition() >= 550 + 32*numberOfBalls) {
                        finished = true;
                    }
                }
            }
            for(BouncingBall ball : balls) {
                ball.erase();
            }
        }
    }
     
    import java.awt.*;
    import java.awt.geom.*;
     
    /**
     * Class BouncingBall - a graphical ball that observes the effect of gravity. The ball
     * has the ability to move. Details of movement are determined by the ball itself. It
     * will fall downwards, accelerating with time due to the effect of gravity, and bounce
     * upward again when hitting the ground.
     *
     * This movement can be initiated by repeated calls to the "move" method.
     * 
     * @author Michael Kölling (mik)
     * @author David J. Barnes
     * @author Bruce Quig
     *
     * @version 2011.07.31
     */
     
    public class BouncingBall
    {
        private static final int GRAVITY = 3;  // effect of gravity
     
        private int ballDegradation = 2;
        private Ellipse2D.Double circle;
        private Color color;
        private int diameter;
        private int xPosition;
        private int yPosition;
        private final int groundPosition;      // y position of ground
        private Canvas canvas;
        private int ySpeed = 1;                // initial downward speed
     
        /**
         * Constructor for objects of class BouncingBall
         *
         * @param xPos  the horizontal coordinate of the ball
         * @param yPos  the vertical coordinate of the ball
         * @param ballDiameter  the diameter (in pixels) of the ball
         * @param ballColor  the color of the ball
         * @param groundPos  the position of the ground (where the wall will bounce)
         * @param drawingCanvas  the canvas to draw this ball on
         */
        public BouncingBall(int xPos, int yPos, int ballDiameter, Color ballColor,
                            int groundPos, Canvas drawingCanvas)
        {
            xPosition = xPos;
            yPosition = yPos;
            color = ballColor;
            diameter = ballDiameter;
            groundPosition = groundPos;
            canvas = drawingCanvas;
        }
     
        /**
         * Draw this ball at its current position onto the canvas.
         **/
        public void draw()
        {
            canvas.setForegroundColor(color);
            canvas.fillCircle(xPosition, yPosition, diameter);
        }
     
        /**
         * Erase this ball at its current position.
         **/
        public void erase()
        {
            canvas.eraseCircle(xPosition, yPosition, diameter);
        }    
     
        /**
         * Move this ball according to its position and speed and redraw.
         **/
        public void move()
        {
            // remove from canvas at the current position
            erase();
     
            // compute new position
            ySpeed += GRAVITY;
            yPosition += ySpeed;
            xPosition +=2;
     
            // check if it has hit the ground
            if(yPosition >= (groundPosition - diameter) && ySpeed > 0) {
                yPosition = (int)(groundPosition - diameter);
                ySpeed = -ySpeed + ballDegradation; 
            }
     
            // draw again at new position
            draw();
        }    
     
        /**
         * return the horizontal position of this ball
         */
        public int getXPosition()
        {
            return xPosition;
        }
     
        /**
         * return the vertical position of this ball
         */
        public int getYPosition()
        {
            return yPosition;
        }
    }
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
     
    /**
     * Class Canvas - a class to allow for simple graphical 
     * drawing on a canvas.
     * 
     * @author Michael Kölling (mik)
     * @author Bruce Quig
     *
     * @version 2011.07.31
     */
     
    public class Canvas
    {
        private JFrame frame;
        private CanvasPane canvas;
        private Graphics2D graphic;
        private Color backgroundColor;
        private Image canvasImage;
     
        /**
         * Create a Canvas with default height, width and background color 
         * (300, 300, white).
         * @param title  title to appear in Canvas Frame     
         */
        public Canvas(String title)
        {
            this(title, 300, 300, Color.white);
        }
     
        /**
         * Create a Canvas with default background color (white).
         * @param title  title to appear in Canvas Frame
         * @param width  the desired width for the canvas
         * @param height  the desired height for the canvas
         */
        public Canvas(String title, int width, int height)
        {
            this(title, width, height, Color.white);
        }
     
        /**
         * Create a Canvas.
         * @param title  title to appear in Canvas Frame
         * @param width  the desired width for the canvas
         * @param height  the desired height for the canvas
         * @param bgClour  the desired background color of the canvas
         */
        public Canvas(String title, int width, int height, Color bgColor)
        {
            frame = new JFrame();
            canvas = new CanvasPane();
            frame.setContentPane(canvas);
            frame.setTitle(title);
            canvas.setPreferredSize(new Dimension(width, height));
            backgroundColor = bgColor;
            frame.pack();
            setVisible(true);
        }
     
        /**
         * Set the canvas visibility and brings canvas to the front of screen
         * when made visible. This method can also be used to bring an already
         * visible canvas to the front of other windows.
         * @param visible  boolean value representing the desired visibility of
         * the canvas (true or false) 
         */
        public void setVisible(boolean visible)
        {
            if(graphic == null) {
                // first time: instantiate the offscreen image and fill it with
                // the background color
                Dimension size = canvas.getSize();
                canvasImage = canvas.createImage(size.width, size.height);
                graphic = (Graphics2D)canvasImage.getGraphics();
                graphic.setColor(backgroundColor);
                graphic.fillRect(0, 0, size.width, size.height);
                graphic.setColor(Color.black);
            }
            frame.setVisible(true);
        }
     
        /**
         * Provide information on visibility of the Canvas.
         * @return  true if canvas is visible, false otherwise
         */
        public boolean isVisible()
        {
            return frame.isVisible();
        }
     
        /**
         * Draw the outline of a given shape onto the canvas.
         * @param  shape  the shape object to be drawn on the canvas
         */
        public void draw(Shape shape)
        {
            graphic.draw(shape);
            canvas.repaint();
        }
     
        /**
         * Fill the internal dimensions of a given shape with the current 
         * foreground color of the canvas.
         * @param  shape  the shape object to be filled 
         */
        public void fill(Shape shape)
        {
            graphic.fill(shape);
            canvas.repaint();
        }
     
        /**
         * Fill the internal dimensions of the given circle with the current 
         * foreground color of the canvas.
         * @param  xPos  The x-coordinate of the circle center point
         * @param  yPos  The y-coordinate of the circle center point
         * @param  diameter  The diameter of the circle to be drawn
         */
        public void fillCircle(int xPos, int yPos, int diameter)
        {
            Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
            fill(circle);
        }
     
        /**
         * Fill the internal dimensions of the given rectangle with the current 
         * foreground color of the canvas. This is a convenience method. A similar 
         * effect can be achieved with the "fill" method.
         */
        public void fillRectangle(int xPos, int yPos, int width, int height)
        {
            fill(new Rectangle(xPos, yPos, width, height));
        }
     
        /**
         * Erase the whole canvas.
         */
        public void erase()
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            Dimension size = canvas.getSize();
            graphic.fill(new Rectangle(0, 0, size.width, size.height));
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Erase the internal dimensions of the given circle. This is a 
         * convenience method. A similar effect can be achieved with
         * the "erase" method.
         */
        public void eraseCircle(int xPos, int yPos, int diameter)
        {
            Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
            erase(circle);
        }
     
        /**
         * Erase the internal dimensions of the given rectangle. This is a 
         * convenience method. A similar effect can be achieved with
         * the "erase" method.
         */
        public void eraseRectangle(int xPos, int yPos, int width, int height)
        {
            erase(new Rectangle(xPos, yPos, width, height));
        }
     
        /**
         * Erase a given shape's interior on the screen.
         * @param  shape  the shape object to be erased 
         */
        public void erase(Shape shape)
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            graphic.fill(shape);              // erase by filling background color
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Erases a given shape's outline on the screen.
         * @param  shape  the shape object to be erased 
         */
        public void eraseOutline(Shape shape)
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            graphic.draw(shape);  // erase by drawing background color
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Draws an image onto the canvas.
         * @param  image   the Image object to be displayed 
         * @param  x       x co-ordinate for Image placement 
         * @param  y       y co-ordinate for Image placement 
         * @return  returns boolean value representing whether the image was 
         *          completely loaded 
         */
        public boolean drawImage(Image image, int x, int y)
        {
            boolean result = graphic.drawImage(image, x, y, null);
            canvas.repaint();
            return result;
        }
     
        /**
         * Draws a String on the Canvas.
         * @param  text   the String to be displayed 
         * @param  x      x co-ordinate for text placement 
         * @param  y      y co-ordinate for text placement
         */
        public void drawString(String text, int x, int y)
        {
            graphic.drawString(text, x, y);   
            canvas.repaint();
        }
     
        /**
         * Erases a String on the Canvas.
         * @param  text     the String to be displayed 
         * @param  x        x co-ordinate for text placement 
         * @param  y        y co-ordinate for text placement
         */
        public void eraseString(String text, int x, int y)
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            graphic.drawString(text, x, y);   
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Draws a line on the Canvas.
         * @param  x1   x co-ordinate of start of line 
         * @param  y1   y co-ordinate of start of line 
         * @param  x2   x co-ordinate of end of line 
         * @param  y2   y co-ordinate of end of line 
         */
        public void drawLine(int x1, int y1, int x2, int y2)
        {
            graphic.drawLine(x1, y1, x2, y2);   
            canvas.repaint();
        }
     
        /**
         * Sets the foreground color of the Canvas.
         * @param  newColor   the new color for the foreground of the Canvas 
         */
        public void setForegroundColor(Color newColor)
        {
            graphic.setColor(newColor);
        }
     
        /**
         * Returns the current color of the foreground.
         * @return   the color of the foreground of the Canvas 
         */
        public Color getForegroundColor()
        {
            return graphic.getColor();
        }
     
        /**
         * Sets the background color of the Canvas.
         * @param  newColor   the new color for the background of the Canvas 
         */
        public void setBackgroundColor(Color newColor)
        {
            backgroundColor = newColor;   
            graphic.setBackground(newColor);
        }
     
        /**
         * Returns the current color of the background
         * @return   the color of the background of the Canvas 
         */
        public Color getBackgroundColor()
        {
            return backgroundColor;
        }
     
        /**
         * changes the current Font used on the Canvas
         * @param  newFont   new font to be used for String output
         */
        public void setFont(Font newFont)
        {
            graphic.setFont(newFont);
        }
     
        /**
         * Returns the current font of the canvas.
         * @return     the font currently in use
         **/
        public Font getFont()
        {
            return graphic.getFont();
        }
     
        /**
         * Sets the size of the canvas.
         * @param  width    new width 
         * @param  height   new height 
         */
        public void setSize(int width, int height)
        {
            canvas.setPreferredSize(new Dimension(width, height));
            Image oldImage = canvasImage;
            canvasImage = canvas.createImage(width, height);
            graphic = (Graphics2D)canvasImage.getGraphics();
            graphic.setColor(backgroundColor);
            graphic.fillRect(0, 0, width, height);
            graphic.drawImage(oldImage, 0, 0, null);
            frame.pack();
        }
     
        /**
         * Returns the size of the canvas.
         * @return     The current dimension of the canvas
         */
        public Dimension getSize()
        {
            return canvas.getSize();
        }
     
        /**
         * Waits for a specified number of milliseconds before finishing.
         * This provides an easy way to specify a small delay which can be
         * used when producing animations.
         * @param  milliseconds  the number 
         */
        public void wait(int milliseconds)
        {
            try
            {
                Thread.sleep(milliseconds);
            } 
            catch (InterruptedException e)
            {
                // ignoring exception at the moment
            }
        }
     
        /************************************************************************
         * Inner class CanvasPane - the actual canvas component contained in the
         * Canvas frame. This is essentially a JPanel with added capability to
         * refresh the image drawn on it.
         */
        private class CanvasPane extends JPanel
        {
            public void paint(Graphics g)
            {
                g.drawImage(canvasImage, 0, 0, null);
            }
        }
    }


    --- Update ---

    the name canvas is given to me by the program

    Ok sorry, below are my three classes. I have been able to get the balls to randomly bounce but not to randomly change size.

    import java.awt.*;
    import java.awt.geom.*;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Random;
    import java.util.ArrayList;
     
    /**
     * Class BallDemo - a short demonstration showing animation with the 
     * Canvas class. 
     *
     * @author Michael Kölling and David J. Barnes
     * @version 2011.07.31
     */
     
    public class BallDemo   
    {
        private Canvas myCanvas;
     
        /**
         * Create a BallDemo object. Creates a fresh canvas and makes it visible.
         */
        public BallDemo()
        {
            myCanvas = new Canvas("Ball Demo", 600, 500);
        }
     
            public void drawFrame() {
            int borderSize = 20;
            Dimension size = myCanvas.getSize();
            Rectangle r = new Rectangle(borderSize, borderSize, (int) size.getWidth() - 2*borderSize, (int) size.getHeight() - 2*borderSize);
            myCanvas.draw(r);
        }
     
     
        /**
         * Simulate two bouncing balls
         */
          public void bounce(int numberOfBalls)
        {
            int ground = 400;   // position of the ground line
            myCanvas.setVisible(true);
            // draw the ground
            myCanvas.drawLine(50, ground, 550, ground);
            // create and show the balls
            Random random = new Random();
            HashSet<BouncingBall> balls = new HashSet<BouncingBall>();
            for(int i=0; i<numberOfBalls; i++) {
                Dimension size = myCanvas.getSize();
                int x = random.nextInt((int) size.getWidth());            
                int y = random.nextInt((int) size.getHeight());
                BouncingBall ball = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
                balls.add(ball);
                ball.draw();
            }
     
     
            // make them bounce
            boolean finished =  false;
            while(!finished) {
                myCanvas.wait(50);           // small delay
                for(BouncingBall ball : balls) {
                    ball.move();
                    // stop once ball has travelled a certain distance on x axis
                    if(ball.getXPosition() >= 550 + 32*numberOfBalls) {
                        finished = true;
                    }
                }
            }
            for(BouncingBall ball : balls) {
                ball.erase();
            }
        }
    }
     
    import java.awt.*;
    import java.awt.geom.*;
     
    /**
     * Class BouncingBall - a graphical ball that observes the effect of gravity. The ball
     * has the ability to move. Details of movement are determined by the ball itself. It
     * will fall downwards, accelerating with time due to the effect of gravity, and bounce
     * upward again when hitting the ground.
     *
     * This movement can be initiated by repeated calls to the "move" method.
     * 
     * @author Michael Kölling (mik)
     * @author David J. Barnes
     * @author Bruce Quig
     *
     * @version 2011.07.31
     */
     
    public class BouncingBall
    {
        private static final int GRAVITY = 3;  // effect of gravity
     
        private int ballDegradation = 2;
        private Ellipse2D.Double circle;
        private Color color;
        private int diameter;
        private int xPosition;
        private int yPosition;
        private final int groundPosition;      // y position of ground
        private Canvas canvas;
        private int ySpeed = 1;                // initial downward speed
     
        /**
         * Constructor for objects of class BouncingBall
         *
         * @param xPos  the horizontal coordinate of the ball
         * @param yPos  the vertical coordinate of the ball
         * @param ballDiameter  the diameter (in pixels) of the ball
         * @param ballColor  the color of the ball
         * @param groundPos  the position of the ground (where the wall will bounce)
         * @param drawingCanvas  the canvas to draw this ball on
         */
        public BouncingBall(int xPos, int yPos, int ballDiameter, Color ballColor,
                            int groundPos, Canvas drawingCanvas)
        {
            xPosition = xPos;
            yPosition = yPos;
            color = ballColor;
            diameter = ballDiameter;
            groundPosition = groundPos;
            canvas = drawingCanvas;
        }
     
        /**
         * Draw this ball at its current position onto the canvas.
         **/
        public void draw()
        {
            canvas.setForegroundColor(color);
            canvas.fillCircle(xPosition, yPosition, diameter);
        }
     
        /**
         * Erase this ball at its current position.
         **/
        public void erase()
        {
            canvas.eraseCircle(xPosition, yPosition, diameter);
        }    
     
        /**
         * Move this ball according to its position and speed and redraw.
         **/
        public void move()
        {
            // remove from canvas at the current position
            erase();
     
            // compute new position
            ySpeed += GRAVITY;
            yPosition += ySpeed;
            xPosition +=2;
     
            // check if it has hit the ground
            if(yPosition >= (groundPosition - diameter) && ySpeed > 0) {
                yPosition = (int)(groundPosition - diameter);
                ySpeed = -ySpeed + ballDegradation; 
            }
     
            // draw again at new position
            draw();
        }    
     
        /**
         * return the horizontal position of this ball
         */
        public int getXPosition()
        {
            return xPosition;
        }
     
        /**
         * return the vertical position of this ball
         */
        public int getYPosition()
        {
            return yPosition;
        }
    }
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
     
    /**
     * Class Canvas - a class to allow for simple graphical 
     * drawing on a canvas.
     * 
     * @author Michael Kölling (mik)
     * @author Bruce Quig
     *
     * @version 2011.07.31
     */
     
    public class Canvas
    {
        private JFrame frame;
        private CanvasPane canvas;
        private Graphics2D graphic;
        private Color backgroundColor;
        private Image canvasImage;
     
        /**
         * Create a Canvas with default height, width and background color 
         * (300, 300, white).
         * @param title  title to appear in Canvas Frame     
         */
        public Canvas(String title)
        {
            this(title, 300, 300, Color.white);
        }
     
        /**
         * Create a Canvas with default background color (white).
         * @param title  title to appear in Canvas Frame
         * @param width  the desired width for the canvas
         * @param height  the desired height for the canvas
         */
        public Canvas(String title, int width, int height)
        {
            this(title, width, height, Color.white);
        }
     
        /**
         * Create a Canvas.
         * @param title  title to appear in Canvas Frame
         * @param width  the desired width for the canvas
         * @param height  the desired height for the canvas
         * @param bgClour  the desired background color of the canvas
         */
        public Canvas(String title, int width, int height, Color bgColor)
        {
            frame = new JFrame();
            canvas = new CanvasPane();
            frame.setContentPane(canvas);
            frame.setTitle(title);
            canvas.setPreferredSize(new Dimension(width, height));
            backgroundColor = bgColor;
            frame.pack();
            setVisible(true);
        }
     
        /**
         * Set the canvas visibility and brings canvas to the front of screen
         * when made visible. This method can also be used to bring an already
         * visible canvas to the front of other windows.
         * @param visible  boolean value representing the desired visibility of
         * the canvas (true or false) 
         */
        public void setVisible(boolean visible)
        {
            if(graphic == null) {
                // first time: instantiate the offscreen image and fill it with
                // the background color
                Dimension size = canvas.getSize();
                canvasImage = canvas.createImage(size.width, size.height);
                graphic = (Graphics2D)canvasImage.getGraphics();
                graphic.setColor(backgroundColor);
                graphic.fillRect(0, 0, size.width, size.height);
                graphic.setColor(Color.black);
            }
            frame.setVisible(true);
        }
     
        /**
         * Provide information on visibility of the Canvas.
         * @return  true if canvas is visible, false otherwise
         */
        public boolean isVisible()
        {
            return frame.isVisible();
        }
     
        /**
         * Draw the outline of a given shape onto the canvas.
         * @param  shape  the shape object to be drawn on the canvas
         */
        public void draw(Shape shape)
        {
            graphic.draw(shape);
            canvas.repaint();
        }
     
        /**
         * Fill the internal dimensions of a given shape with the current 
         * foreground color of the canvas.
         * @param  shape  the shape object to be filled 
         */
        public void fill(Shape shape)
        {
            graphic.fill(shape);
            canvas.repaint();
        }
     
        /**
         * Fill the internal dimensions of the given circle with the current 
         * foreground color of the canvas.
         * @param  xPos  The x-coordinate of the circle center point
         * @param  yPos  The y-coordinate of the circle center point
         * @param  diameter  The diameter of the circle to be drawn
         */
        public void fillCircle(int xPos, int yPos, int diameter)
        {
            Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
            fill(circle);
        }
     
        /**
         * Fill the internal dimensions of the given rectangle with the current 
         * foreground color of the canvas. This is a convenience method. A similar 
         * effect can be achieved with the "fill" method.
         */
        public void fillRectangle(int xPos, int yPos, int width, int height)
        {
            fill(new Rectangle(xPos, yPos, width, height));
        }
     
        /**
         * Erase the whole canvas.
         */
        public void erase()
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            Dimension size = canvas.getSize();
            graphic.fill(new Rectangle(0, 0, size.width, size.height));
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Erase the internal dimensions of the given circle. This is a 
         * convenience method. A similar effect can be achieved with
         * the "erase" method.
         */
        public void eraseCircle(int xPos, int yPos, int diameter)
        {
            Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
            erase(circle);
        }
     
        /**
         * Erase the internal dimensions of the given rectangle. This is a 
         * convenience method. A similar effect can be achieved with
         * the "erase" method.
         */
        public void eraseRectangle(int xPos, int yPos, int width, int height)
        {
            erase(new Rectangle(xPos, yPos, width, height));
        }
     
        /**
         * Erase a given shape's interior on the screen.
         * @param  shape  the shape object to be erased 
         */
        public void erase(Shape shape)
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            graphic.fill(shape);              // erase by filling background color
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Erases a given shape's outline on the screen.
         * @param  shape  the shape object to be erased 
         */
        public void eraseOutline(Shape shape)
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            graphic.draw(shape);  // erase by drawing background color
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Draws an image onto the canvas.
         * @param  image   the Image object to be displayed 
         * @param  x       x co-ordinate for Image placement 
         * @param  y       y co-ordinate for Image placement 
         * @return  returns boolean value representing whether the image was 
         *          completely loaded 
         */
        public boolean drawImage(Image image, int x, int y)
        {
            boolean result = graphic.drawImage(image, x, y, null);
            canvas.repaint();
            return result;
        }
     
        /**
         * Draws a String on the Canvas.
         * @param  text   the String to be displayed 
         * @param  x      x co-ordinate for text placement 
         * @param  y      y co-ordinate for text placement
         */
        public void drawString(String text, int x, int y)
        {
            graphic.drawString(text, x, y);   
            canvas.repaint();
        }
     
        /**
         * Erases a String on the Canvas.
         * @param  text     the String to be displayed 
         * @param  x        x co-ordinate for text placement 
         * @param  y        y co-ordinate for text placement
         */
        public void eraseString(String text, int x, int y)
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColor);
            graphic.drawString(text, x, y);   
            graphic.setColor(original);
            canvas.repaint();
        }
     
        /**
         * Draws a line on the Canvas.
         * @param  x1   x co-ordinate of start of line 
         * @param  y1   y co-ordinate of start of line 
         * @param  x2   x co-ordinate of end of line 
         * @param  y2   y co-ordinate of end of line 
         */
        public void drawLine(int x1, int y1, int x2, int y2)
        {
            graphic.drawLine(x1, y1, x2, y2);   
            canvas.repaint();
        }
     
        /**
         * Sets the foreground color of the Canvas.
         * @param  newColor   the new color for the foreground of the Canvas 
         */
        public void setForegroundColor(Color newColor)
        {
            graphic.setColor(newColor);
        }
     
        /**
         * Returns the current color of the foreground.
         * @return   the color of the foreground of the Canvas 
         */
        public Color getForegroundColor()
        {
            return graphic.getColor();
        }
     
        /**
         * Sets the background color of the Canvas.
         * @param  newColor   the new color for the background of the Canvas 
         */
        public void setBackgroundColor(Color newColor)
        {
            backgroundColor = newColor;   
            graphic.setBackground(newColor);
        }
     
        /**
         * Returns the current color of the background
         * @return   the color of the background of the Canvas 
         */
        public Color getBackgroundColor()
        {
            return backgroundColor;
        }
     
        /**
         * changes the current Font used on the Canvas
         * @param  newFont   new font to be used for String output
         */
        public void setFont(Font newFont)
        {
            graphic.setFont(newFont);
        }
     
        /**
         * Returns the current font of the canvas.
         * @return     the font currently in use
         **/
        public Font getFont()
        {
            return graphic.getFont();
        }
     
        /**
         * Sets the size of the canvas.
         * @param  width    new width 
         * @param  height   new height 
         */
        public void setSize(int width, int height)
        {
            canvas.setPreferredSize(new Dimension(width, height));
            Image oldImage = canvasImage;
            canvasImage = canvas.createImage(width, height);
            graphic = (Graphics2D)canvasImage.getGraphics();
            graphic.setColor(backgroundColor);
            graphic.fillRect(0, 0, width, height);
            graphic.drawImage(oldImage, 0, 0, null);
            frame.pack();
        }
     
        /**
         * Returns the size of the canvas.
         * @return     The current dimension of the canvas
         */
        public Dimension getSize()
        {
            return canvas.getSize();
        }
     
        /**
         * Waits for a specified number of milliseconds before finishing.
         * This provides an easy way to specify a small delay which can be
         * used when producing animations.
         * @param  milliseconds  the number 
         */
        public void wait(int milliseconds)
        {
            try
            {
                Thread.sleep(milliseconds);
            } 
            catch (InterruptedException e)
            {
                // ignoring exception at the moment
            }
        }
     
        /************************************************************************
         * Inner class CanvasPane - the actual canvas component contained in the
         * Canvas frame. This is essentially a JPanel with added capability to
         * refresh the image drawn on it.
         */
        private class CanvasPane extends JPanel
        {
            public void paint(Graphics g)
            {
                g.drawImage(canvasImage, 0, 0, null);
            }
        }
    }
    Last edited by Norm; October 24th, 2013 at 01:16 PM. Reason: Removed QUOTE around code

  10. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    randomly change size.
    What variable holds the size? Where does the code attempt to change it?

    The code does not have a main() method. There is no way to execute it.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need to randomly change the size of programs balls

    size is held in

    class bouncingball

     public BouncingBall(int xPos, int yPos, int ballDiameter, Color ballColor,
                            int groundPos, Canvas drawingCanvas)
        {
            xPosition = xPos;
            yPosition = yPos;
            color = ballColor;
            diameter = ballDiameter;
            groundPosition = groundPos;
            canvas = drawingCanvas;
        }

  12. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    What variable holds the size that you want to change?
    Where does the code attempt to change the contents of that variable?
    If you don't understand my answer, don't ignore it, ask a question.

  13. #11
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need to randomly change the size of programs balls

    yes thats the size

    int ballDiameter = 56+59*i; is changes the size of the ball but its not random

    Random random = new Random();
            HashSet<BouncingBall> balls = new HashSet<BouncingBall>();
            for(int i=0; i<numberOfBalls; i++) {
                Dimension size = myCanvas.getSize();
                int x = random.nextInt((int) size.getWidth());            
                int y = random.nextInt((int) size.getHeight());
                int ballDiameter = 56+59*i;
                BouncingBall ball = new BouncingBall(x, y, ballDiameter, Color.blue, ground, myCanvas);
                balls.add(ball);
                ball.draw();
            }

  14. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    What variable holds the size of the ball when the program is executing?ballDiameter holds its initial value but is not used later.
    Where does the code try to change the size of the ball?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #13
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need to randomly change the size of programs balls

    int ballDiameter = 56+59*i; < thats where the size is changed

    i holds the variable

  16. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    That is where the initial value is set for the diameter of the ball. It is only used once when the ball is created.

    Look at where the ball is drawn. What variable is used to for the size of shape that is drawn?


    The code in post#11 is not in the code in post#7. If you have changed the program, you need to post all of the code so the new version can be tested.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #15
    Junior Member
    Join Date
    Oct 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need to randomly change the size of programs balls

    i have managed to do it thanks for your help

    Random random = new Random();
    HashSet<BouncingBall> balls = new HashSet<BouncingBall>();
    for(int i=0; i<numberOfBalls; i++) {
    Dimension size = myCanvas.getSize();
    int x = random.nextInt((int) size.getWidth());
    int y = random.nextInt((int) size.getHeight());
    int ballDiameter = random.nextInt((int) 50);
    BouncingBall ball = new BouncingBall(x, y, ballDiameter, Color.blue, ground, myCanvas);
    balls.add(ball);
    ball.draw();
    }

  18. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: need to randomly change the size of programs balls

    Glad you got it working.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 2
    Last Post: May 2nd, 2013, 03:35 AM
  2. Re: How to Change JTextArea font, font size and color
    By binokyo10 in forum Java Theory & Questions
    Replies: 1
    Last Post: February 5th, 2012, 11:12 AM
  3. How to Change JTextArea font, font size and color
    By Flash in forum Java Swing Tutorials
    Replies: 7
    Last Post: January 14th, 2012, 09:47 PM
  4. Change font color and size
    By javanovice in forum AWT / Java Swing
    Replies: 2
    Last Post: April 20th, 2010, 09:57 AM
  5. [SOLVED] Change the size of an image
    By subhvi in forum Algorithms & Recursion
    Replies: 4
    Last Post: August 23rd, 2009, 11:44 PM