Solved

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

Posted on 2003-12-09
3
762 Views
Last Modified: 2010-05-18
Hello,
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,
Ken

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.
Timer t = new Timer(20,bp);
t.start();
5. Modify the class BouncePanel so it implements ActionListener. In the actionPerformed()
method:
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));
            this.setBackground(Color.RED);
            this.setLayout(null);
      }

public static void main(String args[]) {
            JFrame jf1 = new JFrame();
            jf1.setSize(700,700);
            jf1.setTitle("BouncePanel1");
            JPanel cp = new JPanel();
            jf1.setContentPane(cp);
            BouncePanel1 bounce1 = new BouncePanel1();
            cp.add(bounce1);
            Bouncer ball1 = new Bouncer(250, Color.YELLOW);
            bounce1.add(ball1);
            ball1.setSize(80,60);
            ball1.setLocation(0,0);
            Bouncer ball2 = new Bouncer(250, Color.CYAN);
            bounce1.add(ball2);
            ball2.setSize(60,40);
            ball2.setLocation(500,0);
            jf1.setVisible(true);
            //Pima.sleep(800);
            ball1.setLocation(200,0);
            ball2.setLocation(300,0);
            Timer t = new Timer(20, bounce1);
            t.start();


      } // 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++) {
                        ((Bouncer)ca[i]).move();
                  }

      }      // 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);
            this.setForeground(c);


      }      // 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;
                  }

                  setCenter(x,y);

      }      // 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

0
Comment
Question by:archeron1
  • 3
3 Comments
 
LVL 92

Accepted Solution

by:
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.

0
 
LVL 92

Expert Comment

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

Expert Comment

by:objects
ID: 9909189
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Understanding websocket example in spring 1 57
thymeleaf natural templating vs JSP 2 68
github account with ecipse 1 42
how to add new optional parameter to JSP 1 29
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

910 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now