Page 1 of 2 12 LastLast
Results 1 to 20 of 32
  1. #1
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Question How to make a bouncing ball in Java

    Okay, I'm trying to make a program that allows the user to create a small blue ball that bounces around the window, using a JPanel to contain the ball and making it bounce off the boundaries. I've got the JPanel and JFrame created, but am stuck at creating the actual ball at the mouse cursor, then incrementing its coords every 20-25 milliseconds.


    Ball.java (defines the ball itself, increments ball coords every 20-25 milliseconds)
    Java Code:
    package com.jlefelhocz.module10;
    
    import java.awt.Color;
    
    public class Ball implements Runnable 
    {
    	int x, y, radius, dx, dy;
    	Color Ballcolor;
    	
    	public Ball(int x,int y,int radius,int dx, int dy, Color bColor)
    	{
    		this.x = x;
    			this.y = y;
    			this.radius = radius;
    			this.dx = dx;
    			this.dy = dy;
    			Ballcolor = bColor;
    	}
    	
    	@Override
    	public void run() 
    	{
    		
    	}
    
    	
    
    }
    RepaintTimer.java(handles the repaint interval, to ensure the ball actually looks like it is moving, a
    Java Code:
    package com.jlefelhocz.module10;
    
    import com.jlefelhocz.module10.BouncingBall;
    
    
    public class RepaintTimer implements Runnable 
    {
    	   
    	  
    	public void run() 
    	{
    		BouncingBall bb = new BouncingBall();
    		bb.repaint();
    	}
    
    	
    	
    }
    
    
    }
    BouncingBall.java (Main class, creates the JFrame that contains the JPanel where the ball spawns, has the main method for sp)

    Java Code:
    package com.jlefelhocz.module10;
    
    import javax.swing.JFrame;
    
    @SuppressWarnings("serial")
    public class BouncingBall extends JFrame 
    {
    
    	  // Box height and width
    	  int width;
    	  int height;
    	 
    	  // Ball Size
    	  float radius = 40; 
    	  float diameter = radius * 2;
    	 
    	  // Center of Call
    	  float X = radius + 50;
    	  float Y = radius + 20;
    	 
    	  // Direction
    	  float dx = 3;
    	  float dy = 3;
    	 
    	
    	public static void main(String[] args) 
    	{
    		JFrame.setDefaultLookAndFeelDecorated(true);
    	    JFrame frame = new JFrame("Bouncing Ball");
    	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    frame.setSize(400, 300);
    	    frame.setContentPane(new BallPanel());
    	    frame.setVisible(true);
    	    
    	}
    	@Override
    	public void repaint()
    	{
    		  while (true) {
    			  
    	          width = getWidth();
    	          height = getHeight();
    	 
    	          X = X + dx ;
    	          Y = Y + dy;
    	 
    	          if (X - radius < 0) {
    	            dx = -dx; 
    	            X = radius; 
    	          } else if (X + radius > width) {
    	            dx = -dx;
    	            X = width - radius;
    	          }
    	 
    	          if (Y - radius < 0) {
    	            dy = -dy;
    	            Y = radius;
    	          } else if (Y + radius > height) {
    	            dy = -dy;
    	            Y = height - radius;
    	          }
    	          repaint();
    	 
    	          try {
    	            Thread.sleep(50);
    	          } catch (InterruptedException ex) {
    	          }
    	 
    	        }
    	}
    }
    
    
    }
    BallPanel.java (The panel where the ball bounces around)
    Java Code:
    package com.jlefelhocz.module10;
    
    
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JPanel;
    
    @SuppressWarnings("serial")
    public class BallPanel extends JPanel 
    {
    	Graphics g;
    	public BallPanel()
    	{
    		addMouseListener(new MouseAdapter()
    				{
    					public void onMouseClicked(MouseEvent e)
    					{
    						Ball b = new Ball(e.getX(), e.getY(), 2, 3, 3, Color.BLUE);
    						
    					}
    				}
    				
    				);
    	}
    	
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    stuck at creating the actual ball at the mouse cursor
    I see a Ball object is created at line 22 in BallPanel, but nothing is done with it.
    What class/method needs to have a reference to that ball to be able to show it at different locations as it moves?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,202
    Rep Power
    12

    Default Re: How to make a bouncing ball in Java

    The one thing you need to focus on is the Ball class. Then you could do the following for a list of Ball objects

    Java Code:
    public void paintComponent(Graphics g) {
        for (Ball b : Balls) {
              b.render(g);
        }
    }
    I recommend that you simply have the ball first bounce up and down and then left and right to ensure that you are handling the boundary conditions correctly. Then you might want to change the x and y increments to vary the slope and see how it bounces off the sides. But the key (imho) is to have all of this done in each instance of the ball class. No other part of the program needs to know anything about the ball class except to call each balls render routine.

    Regards,
    Jim
    Last edited by jim829; 04-16-2018 at 09:38 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    Updated code, now all I need is to figure out how to make my Ball class's run method increment the ball's position every 25 milliseconds, though current run code begins an endless loop of nothing.

    Ball.java:

    Java Code:
    package com.jlefelhocz.module10;
    
    import java.awt.Color;
    import java.awt.Graphics;
    
    public class Ball implements Runnable 
    {
    	int x, y, diameter, dx, dy;
    	Color Ballcolor;
    	
    	
    	
    	public Ball(int x,int y,int diameter,int dx, int dy, Color bColor)
    	{
    		this.x = x;
    			this.y = y;
    			this.diameter = diameter;
    			this.dx = dx;
    			this.dy = dy;
    			Ballcolor = bColor;
    	}
    	
    	@Override
    	public void run() 
    	{
    		while(true) {			 
    	          this.x = x + dx ;
    	          this.y = y + dy;
    	 
    	          if (x - diameter < 0) {
    	            dx = -dx; 
    	            x = diameter; 
    	          } else if (x + diameter > 400) {
    	            dx = -dx;
    	            x = 400 - diameter;
    	          }
    	 
    	          if (y- diameter < 0) {
    	            dy = -dy;
    	            y = diameter;
    	          } else if (y + diameter > 300) {
    	            dy = -dy;
    	            y = 300 - diameter;
    	          }
    	          RepaintTimer rt = new RepaintTimer();
    	          rt.run();
    	 
    	          try {
    	            Thread.sleep(50);
    	          } catch (InterruptedException ex) {
    	          }
    		}
    	}
    
    	
    		
    		
    	public void paint(Graphics g)
    	{
    		g.setColor(Ballcolor);
    		g.fillOval(x,y,diameter,diameter);
    	}
    
    }
    RepaintTimer.java
    Java Code:
    package com.jlefelhocz.module10;
    
    import com.jlefelhocz.module10.BouncingBall;
    
    
    public class RepaintTimer implements Runnable 
    {
    	   
    	  
    	public void run() 
    	{
    		BouncingBall bb = new BouncingBall();
    		bb.repaint();
    	}
    
    	
    	
    }
    BouncingBall.java:
    Java Code:
    package com.jlefelhocz.module10;
    
    import javax.swing.JFrame;
    
    @SuppressWarnings("serial")
    public class BouncingBall extends JFrame 
    {
    
    	  // Box height and width
    int x,y,dx,dy,diameter;
    	 
    	
    	public static void main(String[] args) 
    	{
    		JFrame.setDefaultLookAndFeelDecorated(true);
    	    JFrame frame = new JFrame("Bouncing Ball");
    	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    frame.setSize(400, 300);
    	    frame.setContentPane(new BallPanel());
    	    frame.setVisible(true);
    
    	}
    	@Override
    	public void repaint()
    	{
    		while(true) {
    		
    	          this.x = x + dx ;
    	          this.y = y + dy;
    	 
    	          if (x - diameter < 0) {
    	            dx = -dx; 
    	            x = diameter; 
    	          } else if (x + diameter > 400) {
    	            dx = -dx;
    	            x = 400 - diameter;
    	          }
    	 
    	          if (y- diameter < 0) {
    	            dy = -dy;
    	            y = diameter;
    	          } else if (y + diameter > 300) {
    	            dy = -dy;
    	            y = 300 - diameter;
    	          }
    	          RepaintTimer rt = new RepaintTimer();
    	          rt.run();
    	 
    	          try {
    	            Thread.sleep(50);
    	          } catch (InterruptedException ex) {
    	          }  
    		}
    	}
    }
    BallPanel.java:
    Java Code:
    package com.jlefelhocz.module10;
    
    
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    import javax.swing.JPanel;
    
    @SuppressWarnings("serial")
    public class BallPanel extends JPanel implements MouseListener
    {
    	Graphics g;
    	public BallPanel()
    	{
    		Thread t = new Thread();
    		t.start();
    		addMouseListener(this);
    					
    				
    	}
    	@Override
    	public void mouseClicked(MouseEvent e) {
    		// TODO Auto-generated method stub
    		
    		
    	}
    	@Override
    	public void mouseEntered(MouseEvent e) {
    		// TODO Auto-generated method stub
    		
    	}
    	@Override
    	public void mouseExited(MouseEvent e) {
    		// TODO Auto-generated method stub
    		
    	}
    	@Override
    	public void mousePressed(MouseEvent e) {
    		// TODO Auto-generated method stub
    		Ball b = new Ball(e.getX(), e.getY(), 24, 3, 3, Color.BLUE);
    		b.paint(getGraphics());
    		b.run();
    	}
    	@Override
    	public void mouseReleased(MouseEvent e) {
    		// TODO Auto-generated method stub
    		
    	}
    	
    }

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    The code's design is wrong.
    1)The "loop" to display the ball at its new position should not be a while loop in your code. The "loop" is controlled by the timer method calling repaint and the JVM calling the paintComponent method.
    The steps are:
    begin loop;
    compute the new position (done in timer listener)
    call repaint,
    the JVM calls the paintComponent method that draws the new position,
    wait some (done by Timer),
    go back to begin loop
    2) Use a JPanel to display the ball Not the JFrame
    3) Override paintComponent not repaint in the JPanel. See Jim's post#3
    4) Do not call sleep in the paint method.
    5) The use of a Thread on lines 18&19 does nothing
    Last edited by Norm; 04-16-2018 at 09:58 PM.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    A JPanel is created that holds the ball, I removed the sleep and Thread stuff.

    This is how it is supposed to be built, based on some thoughts:

    The Ball class will implement the Runnable interface. This class defines the ball, and contains accessors getX and getY. The run method of this class is responsible for periodically incrementing the X and Y values of the ball – say every 20 or 25 milliseconds.

    The BallPanel class extends JPanel. This class defines the panel that will contain the bouncing ball.

    The BouncingBall class extends JFrame. This class contains the executable main method. It defines a JFrame which contains the panel defined in BallPanel.

    The RepaintTimer class implements the Runnable interface. The run method of this class is responsible for periodically calling the repaint method of the BouncingBall class – use the same delay as the Ball class.
    Last edited by darthvader45; 04-16-2018 at 11:04 PM.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    The changing of location and the call to repaint could be in the same code. The repainting only needs to be done when the location of the ball has changed. No need to repaint if the ball has not changed location.
    The logic in the paint method would be like jim's suggestion in post#3
    If there is only one ball, there would not be a need for a loop.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    Though if I remove the while loop entirely, for some reason I paint a new ball every time I click the mouse. That's not good.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    I paint a new ball every time I click the mouse.
    What should the code do after a ball is created? Should the mouse listener keep creating a ball after the first one?
    If you want more than one ball, use a collection like jim suggested. Add each new ball to the collection.

    There should not be a while loop in the paint method.
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    I do not have a while loop in the paint method, and I only want the mouse listener to create one ball.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    want the mouse listener to create one ball.
    Then turn off/remove the listener after the ball has been created.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    Alrighty, I have that. But how do I get the ball to move?

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,202
    Rep Power
    12

    Default Re: How to make a bouncing ball in Java

    One way to do it is every time you call repaint, update the x and y positions of the ball. You will also need to check for when the ball "touches" the sides. Then reverse direction by changing the sign of the increment. And it is a given that the signs of the x and y increment will not always be the same.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  14. #14
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    Is there a non-loop way to repeatedly call repaint and my special move method(used to update the ball's coords)?

    move method:

    Java Code:
    public void move() {
    		 x += dx;
    	        y += dy;
    	        
    		if(x + dx < 0 || x + diameter + dx > diameter) {
                x = -dx;
                
            }
            if(y + dy < 0 || y + diameter + dy > diameter) {
                dy = -dy;
                
            }

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    way to repeatedly call repaint
    A repeating Timer call to its listener can do that.
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    So I have a run method that calls them, how would I add a Timer to this to make it repeat?

    Java Code:
    public void run() 
    	{
    		
    		BouncingBall bb = new BouncingBall();
    		bb.repaint();
    		Ball b = new Ball();
    		b.move();
    		
    	}

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    See the API doc for the Timer class. I think it has code samples.

    The code should not create new instances of the BouncingBall class. It must have a reference to an existing instance of the class to call.
    Same with the Ball class. The one and only instance is created by a mouse click.
    If you don't understand my response, don't ignore it, ask a question.

  18. #18
    darthvader45 is offline Member
    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0

    Default Re: How to make a bouncing ball in Java

    So, how should I make sure there are references, as I cannot make static references to non-static methods?

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,949
    Rep Power
    31

    Default Re: How to make a bouncing ball in Java

    A common way is to pass references via the class's constructor.
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,202
    Rep Power
    12

    Default Re: How to make a bouncing ball in Java

    Why are you using static methods? The only static method you would need would be main().

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Page 1 of 2 12 LastLast

Similar Threads

  1. help! bouncing ball program
    By gryd00 in forum New To Java
    Replies: 2
    Last Post: 05-10-2011, 07:58 AM
  2. Bouncing Ball program
    By lost1000 in forum New To Java
    Replies: 3
    Last Post: 11-18-2010, 03:26 PM
  3. high bouncing ball
    By bouncingball in forum Reviews / Advertising
    Replies: 1
    Last Post: 06-19-2008, 11:21 AM
  4. bouncing ball issue
    By adam405 in forum New To Java
    Replies: 1
    Last Post: 03-18-2008, 03:48 AM
  5. Problem deleting ball from bouncing ball app
    By adlb1300 in forum New To Java
    Replies: 2
    Last Post: 12-03-2007, 09:08 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •