Urgent Question: Bouncing Balls in a JPanel (Java 2)

Posted on 2003-12-09
Last Modified: 2010-05-18
this is for an assignment in which I extend a JPanel into a "BouncePanel" and then bounce a couple of balls all over the JPanel. When I run the program, the ball just moves across to the right and disappears from view. I believe that my problem is in how I am writing my if...then statements. I have been over this and over it and I can't figure out how to make multiple balls bounce around.
Thanks much,

Here is a portion of the assignment that I think is most relevant:
3. Also inside Bouncer, define a move() method that will be called every time the timer ticks.
It should:
a. Add xspeed to x, thus moving the ball to a new x-position.
b. If x < 0 the ball is beyond the left edge. Bring it back to the edge by setting x=0, and
reverse the direction of motion by setting xspeed = -xspeed.
c. If x > xmax then the ball is beyond the right edge. Bring it back to the edge by setting
x=xmax and reverse direction by setting xspeed = -xspeed.
d. Repeat steps a,b,c but use y, yspeed, and ymax.
e. Move the ball by calling setCenter() and sending the new x and y values.
4. In the main program, after you do the setVisible(), create a Timer object with a delay of
20 milliseconds (=1/50 second) and tell it to use the bp as its ActionListener. Then start the
Timer t = new Timer(20,bp);
5. Modify the class BouncePanel so it implements ActionListener. In the actionPerformed()
a. Determine the current dimensions of the BouncePanel and store them into the xmax and
ymax variables of class Bouncer. For example
Bouncer.xmax = this.getSize().width;
b. Obtain the array of Components that have been added to this BouncePanel
Component[] ca = this.getComponents();
c. Loop through the array and tell Java to verify that each Component is a Bouncer and then
call the Bouncer's move() method.
d. After moving all the balls, it may be necessary to call bp.repaint() to get them to show.

Java Code is as follows:
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import javax.swing.*;

class BouncePanel1 extends JPanel implements ActionListener {
      BouncePanel1() {
            this.setPreferredSize(new Dimension(600,600));

public static void main(String args[]) {
            JFrame jf1 = new JFrame();
            JPanel cp = new JPanel();
            BouncePanel1 bounce1 = new BouncePanel1();
            Bouncer ball1 = new Bouncer(250, Color.YELLOW);
            Bouncer ball2 = new Bouncer(250, Color.CYAN);
            Timer t = new Timer(20, bounce1);

      } // end method main

      public void actionPerformed(ActionEvent ae) {
                  Bouncer.xmax = this.getSize().width;
                  Component[] ca = this.getComponents();
                  for(int i=0; i<ca.length; i++) {

      }      // end ActionPerformed method

}      // end class BouncePanel

class Bouncer extends JComponent {
      static int xmax, ymax;
      double x, y, xspeed, yspeed;
      int r = 10;
      Bouncer(int r, Color c) {
            this.setSize(2*r, 2*r);

      }      // end Bouncer constructor

      public void setCenter(double x, double y) {
            setLocation((int)x-r, (int)y-r);

      }      // end setCenter method

      public void move() {
            xspeed = 5;
            yspeed = 5;
            x = xspeed + x;
            y = yspeed + y;

            if (x<0) {
                  x = 0;
                  xspeed = -xspeed;
            } else if (x > xmax) {
                  x = xmax;
                  xspeed = -xspeed;

            if (y < 0) {
                  y = 0;
                  yspeed = -yspeed;
                  } else if  (y > ymax) {
                        y = ymax;
                        yspeed = -yspeed;


      }      // end move method

      public void paint( Graphics g ) {
            g.fillOval(0, 0, 2*r, 2*r);
            g.drawString( "Welcome to", 25, 25 );
            g.drawString( "December", 25, 40 );

      } // end paint method

}             // end class Bouncer

Question by:archeron1
  • 3
LVL 92

Accepted Solution

objects earned 500 total points
ID: 9908997
>         xspeed = 5;
>         yspeed = 5;

Don't set speed everytime move() is called. Just initialise it once in your ctor.

LVL 92

Expert Comment

ID: 9909009
unrelated, but you should also override paintComponent() instead of paint() (same args, you just need to change method name).
LVL 92

Expert Comment

ID: 9909189

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 62
netstat -ano | find "8000" and taskkill /f /pid 2984 3 82
throw exception 21 58
eclipse console opening separately 2 29
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question