Help with my Bouncing ball?

Hey guys,
I really have the basis of my program working and everything however i just had one question. My Animation works by using the Alarm which uses the take notice method. The takeNotice then calls a move method that updates my ball coordinates. I am having trouble slowing down the animation. My question is how could I slow down the animation for the viewer without altering the velocity. My set period is at 25 milliseconds that makes the ball animation very smooth however when I increase the milliseconds the animation becomes sloppy and choppy. Does anyone have any ideas of how I could fix this problem???
Thanks guys
The BingBong class which sets up my environment...
     BingBong.java
    This class defines and implements the demo itself.
     It also implements all the methods required to implement a "MouseListener".
import java.awt.*;                                   
import java.awt.event.*;               
import java.awt.geom.*;
public class BingBong extends Frame
                         implements     MouseListener, AlarmListener
//     The instance variables
    private Abutton resetButton,        // My  Buttons
                         throwButton,
                         slowButton,
                         fastButton;          
     private WindowClose myWindow =               //     A handle on the window
                                   new WindowClose();
     private int lastX, lastY;          //     To keep the mouse location
     private Alarm alarm;               //     We use an alarm to wake us up
     private Ball ball;                    // Creating my one ball
//     Constructor
//     ===========
//     The constructor defines a new frame to accommodate the drawing window.
//     It also sets the scene with the visualization of the element
//     and the buttons to manipulate the value of the element.
     public BingBong()
          setTitle("Bing Bong");     //     We set the characteristics of our
          setLocation(50, 50);          //          drawing window
          setSize(420, 450);
          setBackground(Color.pink);
          setVisible(true);                         
          addWindowListener(myWindow);          //     To check on the window
          addMouseListener(this);                    //          and on the mouse
          int x = 53;      // Setting the start points for the button coordiates
          int y = 25;
          resetButton = new Abutton("Reset", Color.red, x, y);
          x += Abutton.BUTTON_WIDTH + 5;
          throwButton = new Abutton("Throw", Color.gray, x, y);
          x += Abutton.BUTTON_WIDTH + 5;
          slowButton = new Abutton("Slower", Color.yellow, x, y);
          x += Abutton.BUTTON_WIDTH + 5;
          fastButton = new Abutton("Faster", Color.green, x, y);
          alarm = new Alarm("Beep", this);     //     We "create" an alarm
          alarm.start();                              //          and we get it started
          alarm.setPeriod(25);                    // The alarm will go off every 35 milliseconds
     public void action()
          System.out.println("\nClick on one of the buttons!\n");
          repaint();   // When the program is launched we will notify the user to click via the console
//     The next method checks where the mouse is been clicked.
//     Each button is associated with its own action.
     private void check()
               if (resetButton.isInside(lastX, lastY)) {
                    ball = null;  // If the reset button is hit the ball will go away
               else if (throwButton.isInside(lastX, lastY)) {
                    double randomX = 380*Math.random();    // Creating a random starting spot for the ball
                    double randomY = 420*Math.random();
                    double randomSpeedX = (9*Math.random()) + 1; //Giving the ball a random speed
                    double randomSpeedY = (7*Math.random()) + 1; // By adding at the end I protect          
                                                                           // in case the random creates a zero
                    ball = new Ball(randomX, randomY, -randomSpeedX, -randomSpeedY);
                    // Calling the Ball constuctor to create a new ball
               else if (slowButton.isInside(lastX, lastY)) {
                    double currentSpeedX = ball.getSpeedX();  // Getting the current ball's speed
                    double currentSpeedY = ball.getSpeedY();
                    double newSpeedX = currentSpeedX - (currentSpeedX/4); // Taking 1/4 of the current speed and
                    double newSpeedY = currentSpeedY - (currentSpeedY/4); // and subtracting it from the current speed
                    ball.setSpeed(newSpeedX, newSpeedY); // Calling the set speed method
               else if (fastButton.isInside(lastX, lastY)) {
                    double currentSpeedX = ball.getSpeedX(); // Getting the current ball's speed
                    double currentSpeedY = ball.getSpeedY();
                    double newSpeedX = (currentSpeedX/4) + currentSpeedX; // Taking 1/4 of the current speed and
                    double newSpeedY = (currentSpeedY/4) + currentSpeedY; // and adding it to the current speed
                    ball.setSpeed(newSpeedX, newSpeedY); // Calling the set speed method
               else  {
                    System.out.println("What?"); // I did not understand the action
               repaint();
//     In order to use an alarm, we need to provide a takeNotice method.
//     It will be invoked each time the alarm goes off.
     public void takeNotice()
          if (ball != null){ // If the ball exists everytime the alarm goes off move the ball
               ball.move();
          repaint();          //     Finally, we force a redrawing
//     The only "graphical" method of the class is the paint method.
     public void paint(Graphics pane)
          if (throwButton != null)               //     When instantiated,
               throwButton.paint(pane);          //     we display all the buttons
          if (slowButton != null)                    
               slowButton.paint(pane);
          if (fastButton != null)
               fastButton.paint(pane);
          if (resetButton != null)                    
               resetButton.paint(pane);
          if (ball != null)                         // Drawing the ball
               ball.paint(pane);
          pane.drawLine(10, 60, 10, 440);     // Using pixel coord. to draw the lines of our "box"
          pane.drawLine(10, 440, 410, 440);
          pane.drawLine(410, 440, 410, 60);
          pane.drawLine(10, 60, 70, 60);
          pane.drawLine(410, 60, 350, 60);
     public void mouseClicked(MouseEvent event)
          check();                                   //     Handle the mouse click
     public void mousePressed(MouseEvent event)
          lastX = event.getX();                    //     Update the mouse location
          lastY = event.getY();
          flipWhenInside();                         //     Flip any button hit by the mouse
     public void mouseReleased(MouseEvent event)
          flipWhenInside();
     public void mouseEntered(MouseEvent event) {}
     public void mouseExited(MouseEvent event) {}
     private void flipWhenInside()
          if (resetButton.isInside(lastX, lastY))  // Flips the buttons to emulate
               resetButton.flip();                  // a push down effect when clicked.
          else if (throwButton.isInside(lastX, lastY))
               throwButton.flip();
          else if (slowButton.isInside(lastX, lastY))
               slowButton.flip();
          else if (fastButton.isInside(lastX, lastY))
               fastButton.flip();
          repaint();
}     // end BingBongMy Ball Class holds its own unique characteristics.....
     Ball.java
     Programmer: Jason Martins
     7/2/08
import java.awt.*;
import java.awt.event.*;
public class Ball
     // My private variables:
     private double x = 0;    // The location of the ball.
     private double y = 0;  
     private Color color = Color.BLUE;
     private double speedX, speedY;  // The speed of my ball.
     private double gravity = 0.098; // The gravity effect (9.8 m per s).
     private double bounceFactor  = 0.97; // The bouncy ness of my ball.
     private final
               double
                    DIAMETER = 21,      // The size of my ball.
                    LEFT_SIDE = 10,
                    RIGHT_SIDE = 410,
                    BOTTOM_BOX = 440;
     // The default constructor for the Ball.
     public Ball(){
     // The Ball constructor will create an
     // ball due its own unique x and y coordinate as well as its speed.
     public Ball(double x, double y, double speedX, double speedY){
          this.x = x;                    // When a new ball is created,
          this.y = y;                    // it will have 4 critical
          this.speedX = speedX;     // doubles. The x and y coordinate and its speed
          this.speedY = speedY;   // horizontally and vertically.
     //     Drawing a ball
     public void paint(Graphics pane)
          pane.fillOval((int) x, (int)y, (int) DIAMETER, (int) DIAMETER);
          // The fillOval method will start from the specfied x and y and draw a oval based on size and height.
     // Will set the color of the given ball, by the specific color passed.
     public void setColor(Color color){
          this.color = color;                    // Sets the color of the ball.
     // Returns the x coordinate the ball is current at.
     public double getX(){
          return x;
     // Returns the y coordinate the ball is current at.
     public double getY(){
          return y;
     // Returns the horizontal velocity of the ball.
     public double getSpeedX(){
          return speedX;
     // Returns the vertical velocity of the ball.
     public double getSpeedY(){
          return speedY;
     // Sets the speed of the ball by the horizontal and vertical velocity passed.
     public void setSpeed(double newSpeedX, double newSpeedY){
          speedX = newSpeedX;
          speedY = newSpeedY;
     // Will move the ball inside the frame depending on numerous factors.
     public void move(){
          x += speedX; // Add horizontal speed to the x location and update the location.
          y += speedY; // Add vertical speed to the y location and update the location.
          speedY += gravity; // Add gravity to the vertical speed and update the vertical speed.
          if(x <= LEFT_SIDE){ // If my x coordinate is equal to the boundry on the left.
               x = LEFT_SIDE;  // The ball bounces reversing the horizontal velocity.
               speedX = -speedX; 
          if(x + DIAMETER >= RIGHT_SIDE){ // If my x coordinate is equal to the boundry on the right.
               x = RIGHT_SIDE - DIAMETER; // The ball bounces reversing the horizontal velocity.
               speedX = -speedX;
          /*if(y <= 60 && x <= 70){
               y = 60;
               x = 70;
               speedY = -speedY;
          if(y <= 60 && x >= 350){
               y = 60;
               x = 350 - DIAMETER;
               speedY = -speedY;
          if(y + DIAMETER >= BOTTOM_BOX){  // If my y coordinate is equal to the boundry on the bottom.
               y = BOTTOM_BOX - DIAMETER;   // The ball bounces reversing the vertical velocity times
               speedY = -speedY *  bounceFactor; // the bouncyness of the ball.
}My Alarm Class.... given to us by our professor
     Alarm.java
                                             A l a r m
                                             =========
     This class defines a basic timer, which "beeps" after a resetable delay.
     On each "beep," the alarm will notify the object registered when the timer
          is instantiated..
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Alarm
                    extends Thread
     private AlarmListener whoWantsToKnow;     //     The object to notify
                                                       //          in case of emergency
     private int delay = 0;                         //     The first beep will occur
                                                       //          without any delay
//     C o n s t r u c t o r s
     public Alarm()
          super("Alarm");                              //     With the default constructor,
          whoWantsToKnow = null;                    //          nobody will be notified
     public Alarm(AlarmListener someBody)
          super("Alarm");                              //     In general,  we expect to know who
          whoWantsToKnow = someBody;               //          (i.e., which object) to notify
     public Alarm(String name, AlarmListener someBody)
          super(name);                              //     We can also give a name to the alarm
          whoWantsToKnow = someBody;
//     The setPeriod method will set or reset the period by which beeps will occur.
//     Note that the new period will be used after reception of the following beep.
     public void setPeriod(int someDelay)
     {                                                  //     Note:  The period should be expressed
          delay = someDelay;                         //                    in milliseconds
//     The setPeriodicBeep method will keep on notifying the "object in charge"
//          at set time intervals.
//     Note that the time interval can be changed at any time through setPeriod.
     private void setPeriodicBeep(int someDelay)
          delay = someDelay;
          try {
               while (true){                              //     For as long as we have energy,
                    Thread.sleep(delay);               //          first we wait
                    if (whoWantsToKnow != null)          //          then we notify the
                         whoWantsToKnow.takeNotice();//          responsible party
               }                                             //          (if anybody wants to hear)
          catch(InterruptedException e) {
               System.err.println("Oh, oh ... " + e.getMessage());
//     The alarm is a Thread, and the run method gets the thread started, and running.
     public void run()
          System.out.println("The alarm is now running.");
          setPeriodicBeep(delay);
}     //     end of class AlarmThanks guys again

One slightly confusing thing is that what you are calling speedX and speedY are not, in fact, the speed of your ball in the X and Y directions. They are the location-change-in-pixels-per-frame values.
The "best" refresh rate has more to do with
(1) the responsiveness of your application: how often it can redraw the screen. This sets an upper limit on the refresh rate. If you try a refresh rate that is too high (ie a delay that is too small) your application won't be able to keep up.
(2) how sensitive the user is to detecting "jerkiness". This sets a lower limit on the refresh rate. If you try a refresh rate that is too low (a delay value that is too big) then the user will at some point complain that the animation is "choppy".
It's a matter of trial and error, but I would start at 20 frames per decond (delay == 50) and see what happens. (The code I posted did that - I haven't run it.) If it appears choppy you can print the time inside your paint() method. This will let you check that you really are repainting every 50ms. If not, then you have exceeded the limit mentioned in (1). That is, your application can't "keep up" and you will need to improve the effeciency of paint().
Say my velocity was 5, if i set my period too 1000 * 5 / (my preferred delay say 50) == 100I'm not completely sure I understand this - if your delay is 50, then the refresh rate must be 1000/50=20 frames per second. You can't change that. If you wanted the ball to move at 5 pixels per second (in the X direction) and your delay was 50 (ie 20fps) then you would find the appropriate speedX value by solving the equation:
5 = 1000 * speedX / 50
speedX = 0.25(Note: 5 pixels per second is not very fast)

Similar Messages

  • Trying to connect the scale parameter with a bouncing ball

    hi, to all
    and thanks for reading this is my first post
    I'm looking for a way to link the scale parameter of a ball to achieve a bounce effect.
    Im trying to use the new link behavior -I used the replicator to replicate a ball then I add the edge collision to it -so far so good the balls are acting ok but now i want to add the scale effect to it when the ball is jumping/ touching the ground
    any idea ????
    thanks
    Gil

    I think it's going to be tough to make that happen - I think it would be easier to simply keyframe it - you can then save the keyframes in a variety of ways:
    http://provideocoalition.com/index.php/smartin/story/reapplyingkeyframes_inmotion/

  • Help with spinning beach ball when I try to open users/accounts in system prefs...I'm using Lion (which I hate) and I need to get into users to change my daughters forgotten password.

    Opening system prefs is fine...when I click on users/accounts, the spinning ball appears and eventually system prefs just closes itself down.
    I've also had a lot of ? Kernel panics....the grey see through screen slowly drops down, the multi language restart writing appears....I restart and it's just the same.
    At the moment it feels like my mac is unusable...should I just uninstall lion and reinstall snow leopard?
    So...system prefs help please and
    Advice re whether or not to uninstall the annoying lion!
    Thanks,
    Nicki

    Ok.....it makes no sense to me (no surprise there I bet).
    The latest one looks like this....
    Mon Aug 29 15:08:42 2011
    panic(cpu 1 caller 0xffffff80002b3126): trying to interlock destroyed mutex (0xffffff80121d52c0)
    Backtrace (CPU 1), Frame : Return Address
    0xffffff808f46bd20 : 0xffffff8000220702
    0xffffff808f46bda0 : 0xffffff80002b3126
    0xffffff808f46bdb0 : 0xffffff7f818f12cc
    0xffffff808f46bdd0 : 0xffffff7f818ef2db
    0xffffff808f46be10 : 0xffffff800053a487
    0xffffff808f46be50 : 0xffffff800057d5b2
    0xffffff808f46bf10 : 0xffffff8000585ab8
    0xffffff808f46bf60 : 0xffffff80005ca258
    0xffffff808f46bfb0 : 0xffffff80002d7f59
          Kernel Extensions in backtrace:
             com.kaspersky.kext.klif(2.1d5)[458E888B-C722-9BC1-926C-4B96147C29FA]@0xffffff7f 818ed000->0xffffff7f81913fff
    BSD process name corresponding to current thread: kav
    Mac OS version:
    11B26
    Kernel version:
    Darwin Kernel Version 11.1.0: Tue Jul 26 16:07:11 PDT 2011; root:xnu-1699.22.81~1/RELEASE_X86_64
    Kernel UUID: D52AAB80-B2BC-3C6E-BBEA-78BD28064998
    System model name: iMac10,1 (Mac-F2268CC8)
    System uptime in nanoseconds: 121502919764
    last loaded kext at 113385384312: com.kaspersky.kext.kimul.37    37 (addr 0xffffff7f8197d000, size 49152)
    loaded kexts:
    com.kaspersky.kext.kimul.37    37
    com.Cycling74.driver.Soundflower    1.5.1
    com.kaspersky.kext.klif    2.1.0d5
    com.apple.driver.AppleBluetoothMultitouch    66.3
    com.apple.driver.AppleHWSensor    1.9.4d0
    com.apple.driver.AudioAUUC    1.59
    com.apple.iokit.IOUserEthernet    1.0.0d1
    com.apple.driver.AppleUpstreamUserClient    3.5.9
    com.apple.driver.AppleMikeyHIDDriver    122
    com.apple.driver.AppleMCCSControl    1.0.24
    com.apple.driver.AppleTyMCEDriver    1.0.2d2
    com.apple.driver.AGPM    100.12.40
    com.apple.driver.AppleMikeyDriver    2.1.1f12
    com.apple.driver.AppleMuxControl    3.0.8
    com.apple.GeForce    7.0.4
    com.apple.Dont_Steal_Mac_OS_X    7.0.0
    com.apple.driver.AppleHDA    2.1.1f12
    com.apple.driver.AirPort.Atheros21    430.14.9
    com.apple.driver.AppleLPC    1.5.1
    com.apple.driver.AppleBacklight    170.1.9
    com.apple.driver.AudioIPCDriver    1.2.0
    com.apple.driver.AirPort.Atheros40    500.55.5
    com.apple.driver.ACPI_SMC_PlatformPlugin    4.7.0b2
    com.apple.filesystems.autofs    3.0
    com.apple.driver.AppleUSBCardReader    3.0.0
    com.apple.iokit.SCSITaskUserClient    3.0.0
    com.apple.driver.AppleIRController    309
    com.apple.BootCache    32
    com.apple.AppleFSCompression.AppleFSCompressionTypeZlib    1.0.0d1
    com.apple.iokit.IOAHCIBlockStorage    2.0.0
    com.apple.AppleFSCompression.AppleFSCompressionTypeDataless    1.0.0d1
    com.apple.driver.AppleFWOHCI    4.8.6
    com.apple.driver.AppleUSBHub    4.4.0
    com.apple.driver.AppleEFINVRAM    1.5.0
    com.apple.driver.AppleAHCIPort    2.1.8
    com.apple.nvenet    2.0.17
    com.apple.driver.AppleUSBEHCI    4.4.0
    com.apple.driver.AppleUSBOHCI    4.4.0
    com.apple.driver.AppleRTC    1.4
    com.apple.driver.AppleHPET    1.6
    com.apple.driver.AppleACPIButtons    1.4
    com.apple.driver.AppleSMBIOS    1.7
    com.apple.driver.AppleACPIEC    1.4
    com.apple.driver.AppleAPIC    1.5
    com.apple.driver.AppleIntelCPUPowerManagementClient    166.0.0
    com.apple.security.quarantine    1
    com.apple.nke.applicationfirewall    3.0.30
    com.apple.driver.AppleIntelCPUPowerManagement    166.0.0
    com.apple.driver.AppleBluetoothHIDKeyboard    152.3
    com.apple.driver.AppleHIDKeyboard    152.3
    com.apple.driver.IOBluetoothHIDDriver    2.5f17
    com.apple.driver.AppleMultitouchDriver    220.62
    com.apple.iokit.IOBluetoothSerialManager    2.5f17
    com.apple.iokit.IOSerialFamily    10.0.5
    com.apple.iokit.IOSurface    80.0
    com.apple.iokit.IOAVBFamily    1.0.0d22
    com.apple.iokit.IOEthernetAVBController    1.0.0d5
    com.apple.driver.AppleHDAHardwareConfigDriver    2.1.1f12
    com.apple.driver.AppleGraphicsControl    3.0.8
    com.apple.driver.DspFuncLib    2.1.1f12
    com.apple.driver.AppleSMBusController    1.0.10d0
    com.apple.driver.AppleBacklightExpert    1.0.3
    com.apple.nvidia.nv50hal    7.0.4
    com.apple.NVDAResman    7.0.4
    com.apple.iokit.IONDRVSupport    2.3
    com.apple.iokit.IOAudioFamily    1.8.3fc11
    com.apple.kext.OSvKernDSPLib    1.3
    com.apple.driver.AppleHDAController    2.1.1f12
    com.apple.iokit.IOGraphicsFamily    2.3
    com.apple.iokit.IOHDAFamily    2.1.1f12
    com.apple.iokit.IO80211Family    400.40
    com.apple.driver.AppleSMC    3.1.1d2
    com.apple.driver.IOPlatformPluginFamily    4.7.0b2
    com.apple.driver.AppleSMBusPCI    1.0.10d0
    com.apple.iokit.IOFireWireIP    2.2.3
    com.apple.kext.triggers    1.0
    com.apple.driver.BroadcomUSBBluetoothHCIController    2.5f17
    com.apple.driver.AppleUSBBluetoothHCIController    2.5f17
    com.apple.iokit.IOBluetoothFamily    2.5f17
    com.apple.driver.AppleFileSystemDriver    13
    com.apple.iokit.IOUSBMassStorageClass    3.0.0
    com.apple.iokit.IOSCSIBlockCommandsDevice    3.0.0
    com.apple.iokit.IOSCSIMultimediaCommandsDevice    3.0.0
    com.apple.iokit.IOBDStorageFamily    1.6
    com.apple.iokit.IODVDStorageFamily    1.6
    com.apple.iokit.IOCDStorageFamily    1.7
    com.apple.iokit.IOUSBHIDDriver    4.4.0
    com.apple.driver.XsanFilter    403
    com.apple.driver.AppleUSBMergeNub    4.4.0
    com.apple.driver.AppleUSBComposite    3.9.0
    com.apple.iokit.IOAHCISerialATAPI    2.0.0
    com.apple.iokit.IOSCSIArchitectureModelFamily    3.0.0
    com.apple.iokit.IOFireWireFamily    4.4.3
    com.apple.iokit.IOUSBUserClient    4.4.0
    com.apple.iokit.IOAHCIFamily    2.0.6
    com.apple.iokit.IONetworkingFamily    2.0
    com.apple.iokit.IOUSBFamily    4.4.0
    com.apple.driver.NVSMU    2.2.9
    com.apple.driver.AppleEFIRuntime    1.5.0
    com.apple.iokit.IOHIDFamily    1.7.0
    com.apple.iokit.IOSMBusFamily    1.1
    com.apple.security.TMSafetyNet    7
    com.apple.security.sandbox    165
    com.apple.kext.AppleMatch    1.0.0d1
    com.apple.driver.DiskImages    326
    com.apple.iokit.IOStorageFamily    1.7
    com.apple.driver.AppleKeyStore    28.18
    com.apple.driver.AppleACPIPlatform    1.4
    com.apple.iokit.IOPCIFamily    2.6.5
    com.apple.iokit.IOACPIFamily    1.4
    Good luck!!!
    Nicki

  • Someone with two macs pls help with spinning beach ball

    Sometimes I download pictures to my MacBook from my camera and then transfer them to my main library on my G5 using photo sharing in iPhoto.
    If "look for shared photos" is enabled on the MacBook and "share my photos" is enabled on the G5, I get a long hang and a spinning beach-ball in when I launch iPhoto on the MacBook The hang seems subsequently affects the G5. They both hang for a good 15-30 seconds.
    While this is happening the Application Monitor shows a root process called "mds" using 99% of the MacBook CPU. Once the hang is over the mds process goes away. The G5 while still hanging simply shows iPhoto as not responding, no mds process.
    I've wiped the MacBook clean, set up new accounts. Nothing seems to fix it. The question is; am I alone? Can someone else go through the steps and get iPhoto to launch with iPhoto already running on another networked mac with photo sharing enabled and not get a spinning beach-ball.
    This was also a problem in iPhoto 06'. I was really hoping Apple got my feedback and fixed in 08' Maybe something is wrong with my MacBook.

    Hi.
    mds is the indexing process, usually run by Spotlight when looking for files, folders, servers, etc.
    that's the reason why you get the delay when seeking your images using the sharing function. Your mac is searching for the requested service (your photo sharing "server"...your other mac), and it cannot find it because of the firewall that's built in to the mac. Whether you're doing this via a wireless or an Ethernet connection, you'll need to assure that your firewalls on
    both computers are open to allow that type of sharing to take place.
    Take a look in your System Prefs, under the Sharing icon. Click on the "Firewall" button and, after authenticating with your password, scroll down and select the option for "iPhoto Bonjour Sharing". You'll need to do this on BOTH machines, as the port is used by each for communication.
    That should solve the problem..
    Cheers,
    Charlie

  • Java Bouncing Balls Threads problem?

    Hello,
    I am working on a homework assignment to represent a java applet with some bouncing balls inside. So far so good. The balls bounce and behave as they are supposed. The only thing is that I want to make 2 buttons, Start and Stop (this is not part of the assignment, but my free will to provide some extra stuff :) ) . I am implementing Runnable for the animation and ActionListener for the buttons. I did research on threading, but somehow I am still not getting quite the result I want. The applet is not displaying my buttons (I guess I am not implementing them correctly) and I dont know whether I have synchronized the threads correctly as well. So, I am asking for some guidance how can I do this? Thanks in advance!
    As a remark, I am new to Java, as I am just starting to learn it and this is my first assignment.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    public class Balls extends JApplet implements Runnable, ActionListener
         Thread runner = null;     
         Image img;
        Graphics gr;          
        BallCollision ball[];
        Balls can;
        JButton stopButton;
        JButton startButton;
        JPanel controls;
        boolean stop,start;
        //field for 10 balls
        static final int MAX=10;
         public void init()
              setSize(800,600);
              img = createImage(size().width,size().height);
              gr = img.getGraphics();     
              startButton = new JButton("Start");
              stopButton = new JButton("Stop");
              stopButton.addActionListener(this);
              startButton.addActionListener(this);
              controls = new JPanel();
              controls.setLayout(new FlowLayout());
              controls.add(startButton);
              controls.add(stopButton);
              //new Thread(this).start();
              ball = new BallCollision[MAX];
              int w=size().width;
              int h=size().height;          
              //creation of balls, which have different coordinates,
              //speed, direction and colors
              ball[0] = new BallCollision(w,h,50,20,1.5,7.5,Color.orange);
            ball[1] = new BallCollision(w,h,60,210,2.0,-3.0,Color.red);
            ball[2] = new BallCollision(w,h,15,70,-2.0,-2.5,Color.pink);
            ball[3] = new BallCollision(w,h,150,30,-2.7,-1.0,Color.cyan);
            ball[4] = new BallCollision(w,h,210,30,2.2,-12.5,Color.magenta);
              ball[5] = new BallCollision(w,h,360,170,2.2,-1.5,Color.yellow);
              ball[6] = new BallCollision(w,h,210,180,-1.2,-2.5,Color.blue);
              ball[7] = new BallCollision(w,h,330,30,-2.2,-1.8,Color.green);
              ball[8] = new BallCollision(w,h,180,220,-2.2,-1.8,Color.white);
              ball[9] = new BallCollision(w,h,330,130,-2.2,9.0,Color.gray);     
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == startButton) start = true;
                   can.start();
              if(e.getSource() == stopButton) start = false;
                   can.stop();
         public void start()
              if (runner == null)
                   runner = new Thread (this);
                   runner.start();
         public void stop()
              if (runner != null)
                  runner.stop();
                    runner = null;
         public void run()
              while(true)
                   try {Thread.sleep(15);}
                     catch (Exception e) { }               
                   //move our balls around
                   for(int i=0;i<MAX;i++)
                        ball.move();
                   handleCollision();
                   repaint();     
         boolean collide(BallCollision b1, BallCollision b2)
              double wx=b1.getCenterX()-b2.getCenterX();
              double wy=b1.getCenterY()-b2.getCenterY();
              //the distance between 2 colling balls' centres is
              //calculated by the theorem of Pythagoras
              double distance=Math.sqrt(wx*wx+wy*wy);
              if(distance<b1.diameter)
                   return true;          
                   return false;     
         private void handleCollision()
              //ecah ball is checked for possible collisions
              for(int i=0;i<MAX;i++)
                   for(int j=0;j<MAX;j++)
                             if(i!=j)
                                  if(collide(ball[i], ball[j]))
                                       ball[i].hit(ball[j]);
                                       ball[j].hit(ball[i]);
         public void update(Graphics g)
              paint(g);
         public void paint(Graphics g)
              gr.setColor(Color.black);
              gr.fillRect(0,0,size().width,size().height);          
              //paint the balls
              for(int i=0;i<MAX;i++)
                        ball[i].paint(gr);          
              g.drawImage (img,0,0, this);                    
    class BallCollision
         int width, height;
         int diameter=30;
         //balls' coordinates and values to be incremented for directions
         double x, y, xIncremented, yIncremented, coll_x, coll_y;
         boolean collide;
         Color color;
         Graphics g;
         //constructor
         public BallCollision(int w, int h, int x, int y, double xInc, double yInc, Color c)
              width=w;
              height=h;
              this.x=x;
              this.y=y;
              this.xIncremented=xInc;
              this.yIncremented=yInc;          
              color=c;          
         public double getCenterX() {return x+diameter/2;}
         public double getCenterY() {return y+diameter/2;}
         public void move()
              if (collide)
                   double xvect=coll_x-getCenterX();
                   double yvect=coll_y-getCenterY();
                   if((xIncremented>0 && xvect>0) || (xIncremented<0 && xvect<0))
                        xIncremented=-xIncremented;
                   if((yIncremented>0 && yvect>0) || (yIncremented<0 && yvect<0))
                        yIncremented=-yIncremented;
                   collide=false;
              x+=xIncremented;
         y+=yIncremented;
              //if the ball reaches a wall, it bounces to the opposite direction
         if(x<1 || x>width-diameter)
              xIncremented=-xIncremented;
                   x+=xIncremented;
              if(y<1 || y>height-diameter)
                   yIncremented=-yIncremented;
                   y+=yIncremented;
         public void hit(BallCollision b)
              if(!collide)
                   coll_x=b.getCenterX();
                   coll_y=b.getCenterY();
                   collide=true;
         public void paint(Graphics graphics)
              g=graphics;
              g.setColor(color);
              //the coordinates in fillOval have to be int, so we cast
              //explicitly from double to int
              g.fillOval((int)x,(int)y,diameter,diameter);

    well i didnt arrive at this point without reading tutorials and researching.... sometimes other people can spot your mistakes a lot easier than you can, that's why I asked for help. 10x anyway for the interest!

  • Bouncing ball question

    Hi, I'm new to the forums and really new to java and I was wondering if anyone could help me with a simple java program that I'm writing.
    It deals simply with a bouncing ball (yes I know there's a topics on this one heh) that bounces aimlessly inside a drawing window.
    Here's my problem:
    I can make the ball bounce off two boundaries (top and right, left and bottom, right and bottom etc.) but when the ball reaches the 3rd boundary it just passes through it. It wont bounce off opposite sides (left and right, top and bottom) it only bounces off the first.
    I believe it has something to do with my if statements under the move method.
    I need to make some kind of loop so it keeps checking if the ball comes to a new boundary.
    Right now it's only checking it once and after it bounces the ball one time thats it.
    (I've tested all the boundaries to see if they bounce the ball and they all do, its just I can't bounce it more than 2 times)
    I'm stuck on how to write this loop statement. Any help would be greatly appreciated! Thanks.
    My code (If this isnt enough let me know please):
    (BallTester.java)
    import element.*;
    public class BallTester{
    public static void main(String[] args){
    int width = 500;
    int height = 400;
    DrawingWindow d = new DrawingWindow(width,height);      
    Ball b = new Ball(70,30,width,height);
    b.send(d);                                   
    (Ball.java)
    import element.*;
    public class Ball{
    int base; // center line of where the circle starts
    int size; // radius of circle
    int xPos,yPos; // circle ctr
    Circle c;
         int width, height;
         int dx,dy;
    public Ball(int base, int size, int width, int height) {
              this.base = base;
    this.size = size;
    c = new Circle(50,base,size);
              this.width = width; this.height = height;
              xPos = 50;
              yPos = base;
    public void drawOn(DrawingWindow d){
              //draws the circle
              c.drawOn(d);
    public void clearOn(DrawingWindow d){
              d.invertMode(); // black-> white
              drawOn(d); //redraw in white: erase!
              d.invertMode(); // white -> black
    public void move(int dx, int dy){
              //Sets boundaries for x values
              if((xPos<=size)||(xPos>=width-size)){
              dx = -dx;
              else
              xPos += dx;
              //Sets boundaries for y values
              if((yPos<=size)||(yPos>=height-size)){
              dy = -dy;
              else     
              yPos += dy;
              c.move(dx,dy);
    public void send(DrawingWindow d){
              Waiting w = new Waiting();
    //This below keeps the ball drawing up until j = width)
    for(int j = 0; j < width; j++){
              move(6,-3); // moves the circle based on dx, dy values
              this.drawOn(d);
    w.snooze(60);
    this.clearOn(d);}

    You don't need a loop to check - you just need to check every loop (before you repaint).
    I created an example for you. If this assignment is homework, don't hand it in - use it as a reference. Try to understand what's going on in the code and why it works.
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (new TestPanel ());
            setDefaultCloseOperation (DISPOSE_ON_CLOSE);
            setTitle ("Test");
            pack ();
            setLocationRelativeTo (null);
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
        private class TestPanel extends JPanel {
            private Ball ball;
            public TestPanel () {
                ball = new Ball ();
                Thread painter = new Thread (new Runnable () {
                    public void run () {
                        while (true) {
                            try {
                                Thread.sleep (20);
                            } catch (InterruptedException exception) {}
                            repaint ();
                painter.setDaemon (true);
                painter.start ();
            public Dimension getPreferredSize () {
                return new Dimension (300, 200);
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                ball.move (getWidth (), getHeight ());
                ball.paint (g);
            private class Ball {
                private static final int W = 10;
                private static final int H = 10;
                private int x;
                private int y;
                private int dx;
                private int dy;
                public Ball () {
                    x = 0;
                    y = 0;
                    dx = 2;
                    dy = 2;
                public void move (int width, int height) {
                    int x = this.x + dx;
                    int y = this.y + dy;
                    if ((x < 0) || (x + W > width)) {
                        dx = -dx;
                        x = this.x + dx;
                    if ((y < 0) || (y + H > height)) {
                        dy = -dy;
                        y = this.y + dy;
                    this.x = x;
                    this.y = y;
                public void paint (Graphics g) {
                    g.fillOval (x, y, W, H);
    }

  • Please can anyone help with the continuing password rejection problem with email.Ipad and other systems work fine but despite reloading my password on imac it bounces back.Apple store has been visited and I have tried everything they suggest.

    Please can anyone help with the continuing password rejection problem with email on my imac.My Ipad and other systems work fine but despite reloading my password on imac it bounces back.Apple store has been visited and I have tried everything they suggest.

    I use free Yahoo mail webMail access because folders I created in webmail access doesn't get set up in Apple Mail. While I was searching for post about password and keychain issues, I stumbled on several threads that complain about Mail folder issues, so I'm holding off on Apple Mail.
    On the password and keychain issue that your post is all about.  I've been using login keychain to save and automatical fill my login screens for a year or so successfully, with Safari and Chrome. Automatic form fill also works for Facebook login. Unfortunately, about 4 to 6 months ago, automatic password form fill stopped working with Yahoo webmail, while still worked for GMail (Safari and Chrome). I tried deleting the password entry for my two Yahoo email accounts to start fresh, but neither Safari not Chrome will even ask me if I want to save the password. I was so frustrated that I eventually installed the keypassX 0.43 (password manager) that is quite primitive sompare to OS X's keychain (when it works). Probably no surprise to you yet.
    The surprise, to me at least, is that, for whatever reason, password auto form-fill from keychain started working again for Yahoo webmail login on Safari about 5-7 days ago. Still doesn't work on Chrome!
    Two tips I can share, at least with webmail access:
    1. Password is save only for one of my yahoo mail accounts. When I login in with my other yahoo account, I get no prompt to save the password, and form fill doesn't work when I try to log in a second time with my other Yahoo mail account.
    2. On inspection of my login keychain, I see a webform password item saved for my Yahoo account that works with keychain. The name of the password is: login.yahoo.com(MyAccountName1#). When I open the password item and look in the Access Control tab, I see Safari and Chome are listed as allowed to access this password item..
         I also an "Internet password" item with a name of just login.yahoo.com. When I open the the password item, it looks just like the password item created for MyAccountName#1, but the MyAccountName#2 is listed in the Account field. Inside the Access Control tab, no apps are listed in access permission. I added Safari and Chrome to the lists of allowed app, saved the password item.
    Now when I bring up the Yahoo login page(by bookmark) on Safari, form fill fills in MyAccountname#1 for name and the proper password and I can login in. When I change the name to MyAccountName#2, the correct password is retrieved and I can log in! Alas, it still doesn't work on Chrome.
    BTW, I changed the password item type from "Internet password" to "Web Form password" and saw no difference! I also edited the name to be "login.yahoo.com (MyAccountName#2)" to look like the web form password item that works, but it has no effect either.
    From my experimentation, here's my observation:
    1. A Web Form password item is created for the first account name(MyAccountName#1) for login.yahoo.com and typed as Web Form password. When I log in using MyAccountName#2, an Internet Password is created, but no applications are listed as allowed to access the password item, even when the password item was created after just logged in and logged out to yahoo with the account name and password for MyAccountName#2.
    2. Manually adding Safari as an app that is allowed to use the password item works. Doesn't work with Chrome!
    The version of Safari I'm using is Version 5.1.7 (6534.57.2). My installed version of Chrome is Version 21.0.1180.79 beta.

  • Balls don't move in bouncing balls game.Please Help !?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package ****;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("****");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  This code draws only the first position of the ball:
    http://img267.imageshack.us/my.php?image=51649094by6.jpg

    I'm trying to draw everything first to a buffer:
    buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
    gBuffer=buffer.getGraphics();
    The buffer is for one JPanel and then i want to draw this buffer every time when balls change their possitions(collide or just move).
    The logic is something like this:
    startButton -> (ball.start() and add ball to List<balls>),
    ball.start() -> ball.run() -> (move allballs, paint to buffer and show buffer)
    In the first class:
    BouncingBalls balls; //A REFERENCE TO SECOND CLASS
    In the second class:
    private List<CollideBall> balls=new ArrayList();
    the tames are the same but this isn't an error.
    Edited by: vigour on Feb 14, 2008 7:57 AM

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Many Bouncing Balls Program

    I am trying to create a program that can use one method to create many bouncing balls.I want each ball to function independently of each other.
    The problem I am having is that when I call my BouncingBall () method three times, it only creates one ball that moves randomly instead of three.
    If you have any idea of how to tackle this problem I would really appreciate if you shared them with me. I am relatively new to java.
    I read that threads might be a good option to work on this problem but I am not sure how to use them.
    *(Code Starts)*
    import acm.graphics.*;
    import acm.program.*;
    import acm.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BouncingBalls extends GraphicsProgram {
         public void run(){
              BouncingBall(50, 50);
              BouncingBall(100, 100);
              BouncingBall(300, 300);
         public void BouncingBall(double width, double height) {
              //Create variables for x and y position of balls
              double xPosition = getWidth()/2;
              double yPosition = getHeight()/2;
              //Create Ball
              GOval Ball = new GOval (xPosition, yPosition, width, height);
              add (Ball);
              // Initialize variables for use in Random movement method
              double xMoveBall = rgen.nextDouble(-4.0, 4.0);
              double yMoveBall = rgen.nextDouble(-4.0, 4.0);
              //Ball's Random Movement
              while (true) {     
                        Ball.move(xMoveBall,yMoveBall);
                        pause(10);
                             xPosition += xMoveBall;
                             yPosition += yMoveBall;
                   //Ball's Collisions     with walls
                   if (xPosition >= (getWidth() - width)) {
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (xPosition <= 0){
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (yPosition <= 0){
                        yMoveBall = -(yMoveBall);
                        pause(10);
                   if (yPosition >= getHeight() - height){
                        yMoveBall = -(yMoveBall);
                        pause(10);
         private RandomGenerator rgen = RandomGenerator.getInstance();{}
    *(Code Ends)*

    Hi,
    I have been experimenting with threads for the last couple of days. Here is the code I have been working on. I explain what I am trying to do below it:
    import acm.graphics.*;
    import acm.program.*;
    import acm.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BB5 extends GraphicsProgram implements Runnable{
         // Debbuging Label
         private GLabel label = new GLabel("");
         //Initialize variables for ball's position
         private double xPosition = getWidth()/2;
         private double yPosition = getHeight()/2;
         //Initialize variables for use in Random movement method
         private double yMoveBall;
         private double xMoveBall;
         //Initialize variables for width and height of ball, so that they can be used in both metods: bounce() and CreateBall()
         private double width;
         private double height;
         public void mouseClicked (MouseEvent e){
              new Thread(this).start();
         public void run() {
              CreateBall(50,50).bounce();
         public void CreateBall(double x, double y) {
              //Create variables for x and y position of balls
                 xPosition = getWidth()/2;
                 yPosition = getHeight()/2;
              //Create Ball
              x = width;
              y = height;
              GOval Ball = new GOval (xPosition, yPosition, width, height);
              add (Ball);
         public void bounce() {     
         yMoveBall = rgen.nextDouble(-4.0, 4.0);
         xMoveBall = rgen.nextDouble(-4.0, 4.0);
              //Ball's Random Movement
              while (true){
                   //Put thread to sleep for 5 milliseconds so that other balls can use bounce()
                   try { Thread.sleep(5); } catch(InterruptedException e) {}
                        //Move Ball created in previous methods
                        Ball.move(xMoveBall,yMoveBall);
                        pause(10);
                             xPosition += xMoveBall;
                             yPosition += yMoveBall;
                             label.setLabel(""+xPosition); add (label, 50, 50);
                   //Ball's Collisions     with walls
                   if (xPosition >= (getWidth() - width)) {
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (xPosition  <= 0){
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (yPosition  <= 0){
                        yMoveBall = -(yMoveBall);
                        pause(10);
                   if (yPosition  >= getHeight() - height){
                        yMoveBall = -(yMoveBall);
                        pause(10);
         private RandomGenerator rgen = RandomGenerator.getInstance();{}
    }The idea is that I have a method that creates the ball CreateBall(), and another that bounces the ball bounce().
    My init method creates one ball. Then, when I click the mouse, I create a new thread which applies the bounce method to the ball by running the run method.
    Inside the bounce method, I have a thread sleep so that other threads can be started.
    Eventually, what I would like to do, is that everytime I click the mouse, a new ball is created and the bounce is applied to it.
    I am also having trouble with getting the ball from my CreateBall() method, to work inside my bounce().
    Can you please help me understand what might be wrong with my code?
    Thank you!

  • Mac is way too slow and bouncing ball is constant

    I ran the etrecheck and this is what it came back with.  What should I do?
    Problem description:
    Bouncing ball all the time…computer super slow.
    EtreCheck version: 2.1.7 (114)
    Report generated January 31, 2015 at 5:37:13 PM PST
    Download EtreCheck from http://etresoft.com/etrecheck
    Click the [Support] links for help with non-Apple products.
    Click the [Details] links for more information about that line.
    Click the [Adware] links for help removing adware.
    Hardware Information: ℹ️
        MacBook Pro (15-inch, Early 2011) (Technical Specifications)
        MacBook Pro - model: MacBookPro8,2
        1 2 GHz Intel Core i7 CPU: 4-core
        4 GB RAM Upgradeable
            BANK 0/DIMM0
                2 GB DDR3 1333 MHz ok
            BANK 1/DIMM0
                2 GB DDR3 1333 MHz ok
        Bluetooth: Old - Handoff/Airdrop2 not supported
        Wireless:  en1: 802.11 a/b/g/n
        Battery Health: Normal - Cycle count 263
    Video Information: ℹ️
        Intel HD Graphics 3000 - VRAM: 384 MB
        AMD Radeon HD 6490M - VRAM: 256 MB
            Color LCD 1440 x 900
    System Software: ℹ️
        OS X 10.10.2 (14C109) - Time since boot: 0:13:39
    Disk Information: ℹ️
        ST9500325ASG disk0 : (500.11 GB)
            EFI (disk0s1) <not mounted> : 210 MB
            Recovery HD (disk0s3) <not mounted>  [Recovery]: 650 MB
            Macintosh HD (disk1) / : 498.88 GB (235.63 GB free)
                Core Storage: disk0s2 499.25 GB Online
        HL-DT-ST DVDRW  GS23NR 
    USB Information: ℹ️
        Apple Inc. FaceTime HD Camera (Built-in)
        HP Photosmart Plus B210 series
        Apple Inc. Apple Internal Keyboard / Trackpad
        Apple Inc. BRCM2070 Hub
            Apple Inc. Bluetooth USB Host Controller
        Apple Computer, Inc. IR Receiver
    Thunderbolt Information: ℹ️
        Apple Inc. thunderbolt_bus
    Gatekeeper: ℹ️
        Mac App Store and identified developers
    Kernel Extensions: ℹ️
            /System/Library/Extensions
        [loaded]    com.LaCie.ScsiType00 (1.2.9 - SDK 10.6) [Support]
        [loaded]    com.jmicron.driver.jmPeripheralDevice (2.0.4) [Support]
        [not loaded]    com.kaspersky.kext.klif (3.0.0d23) [Support]
        [loaded]    com.kaspersky.nke (1.0.2d43) [Support]
        [loaded]    com.lacie.driver.LaCie_RemoteComms (1.0.1 - SDK 10.4) [Support]
        [loaded]    com.oxsemi.driver.OxsemiDeviceType00 (1.28.13 - SDK 10.5) [Support]
    Launch Daemons: ℹ️
        [loaded]    com.adobe.fpsaud.plist [Support]
        [running]    com.fitbit.galileod.plist [Support]
    User Launch Agents: ℹ️
        [loaded]    com.adobe.ARM.[...].plist [Support]
    User Login Items: ℹ️
        iTunesHelper    Application Hidden (/Applications/iTunes.app/Contents/MacOS/iTunesHelper.app)
    Internet Plug-ins: ℹ️
        FlashPlayer-10.6: Version: 16.0.0.296 - SDK 10.6 [Support]
        QuickTime Plugin: Version: 7.7.3
        Flash Player: Version: 16.0.0.296 - SDK 10.6 [Support]
        Default Browser: Version: 600 - SDK 10.10
        SharePointBrowserPlugin: Version: 14.3.9 - SDK 10.6 [Support]
        Silverlight: Version: 5.1.20913.0 - SDK 10.6 [Support]
        JavaAppletPlugin: Version: 15.0.0 - SDK 10.10 Check version
    Safari Extensions: ℹ️
        Pin It Button [Installed]
    3rd Party Preference Panes: ℹ️
        Flash Player  [Support]
    Time Machine: ℹ️
        Skip System Files: NO
        Mobile backups: ON
        Auto backup: YES
        Volumes being backed up:
            Macintosh HD: Disk size: 498.88 GB Disk used: 263.25 GB
        Destinations:
            LaCie [Local]
            Total size: 499.76 GB
            Total number of backups: 11
            Oldest backup: 2013-04-08 05:32:50 +0000
            Last backup: 2014-12-29 20:32:29 +0000
            Size of backup disk: Too small
                Backup size 499.76 GB < (Disk used 263.25 GB X 3)
    Top Processes by CPU: ℹ️
             5%    WindowServer
             0%    systemstatsd
             0%    HP Scanner 3
             0%    AppleSpell
             0%    fontd
    Top Processes by Memory: ℹ️
        232 MB    Image Capture Extension
        159 MB    ocspd
        133 MB    Safari
        120 MB    com.apple.WebKit.WebContent
        94 MB    Dock
    Virtual Memory Information: ℹ️
        40 MB    Free RAM
        1.56 GB    Active RAM
        1.53 GB    Inactive RAM
        1.14 GB    Wired RAM
        1.40 GB    Page-ins
        5 MB    Page-outs
    Diagnostics Information: ℹ️
        Jan 31, 2015, 05:24:14 PM    Self test - passed

    I can't stand peremptory affirmations like "Nothing is wrong with Safari".
    Thousands of users can't be wrong (see the discussions).
    If I read you the right way, it's never software' fault, it's the user who's the culprit.
    Amazing!
    In this very case, the fact is we can't give to "christinefromfonthill" a good solution because weren't sitting in front of her Mac.
    You give her a good advice which could, perhaps, lead to an improvement.
    But must also admit that Safari is a very slow browser compared to Firefox or Chrome.
    And you can't ignore all the problems which arose when upgrading to Lion and were related to the new build and specs of Safari 5.1.
    The best example is the apparition of "garbage type" (use of Last Resort font) when reading numerous sites. This never occured before and is the direct consequence of Safari compliance to Web Open Type. This standard prohibits the use of Type 1 Postscript Fonts and is the reason why so many people are in trouble.
    I use a Mac for more than 25 years.
    I am a very "clean" user who hates the bells and whistles of third party.
    My Mac is always up-to-date and despite all my Mac loving care, I run into some problems.
    Imagine the nightmare which can occurs for the vulgum pecus who isn't, by definition, a power user aware of all the requirements for running a System in optimal conditions.
    May be Safari is one step in advance on its time but lambda users are paying the price for it.

  • Help with Trees in java!

    I have an assignment to create a bouncing ball, with collision detection, and obstacles, and to also include trees.
    I have managed to get a bouncing ball(using awt graphics), but I am having problems with the tree, as i do understand that the dimensions for my canvas/boundary area for my ball will be the root node, and for each of my child node, will be the grid with my obstacle in it(the data in it will be the coordinates for each grid
    However, I still don't know what to do as I can easily explain a program, but i cant put it into programming sense, so if anyone knows exactly how to code a tree program to include my grid layouts, and my bouncing ball..........
    N.B I am not sure if i really pointed out what the problem is, however if you need me 2 post my code up, or explain myself further, I will be very happy to do that.
    I also need help on how to create the grid(not sure if i need one), i am soo confused!!
    Thanks for any help in advance
    Message was edited by:
    tawa
    Message was edited by:
    tawa

    I can easily explain a programReally? But can you explain it in such a way that somebody else understands your explanation? If so, then this would be a good time to do that.
    For example I don't understand what trees have to do with your description. The best guess that I can make is that they are some kind of vegetation that gets in the way of your bouncing balls.

  • Help with some simple coding

    Hello
    I am very new to Java and am currently studying a course in the language.
    I am working through a tutorial at the moment and a question has been asked and I am struggling a bit
    I have been given the code to a program that creates a window with a ball bouncing around inside the window.
    There are 2 classes (code below) - Call class - this contains all the code need to create the ball and BallWorld Class (the main Class) this create the window and moves the ball, it also detects if the ball hits the edge of the window, whne this happens it redirects the ball. I understand how all this code works
    I have been asked the following:-
    Rather than testing whether or not the ball has hit the wall in the nmain program, we could use inhertitance to provide a specialized forom of Ball. Create a class BoundedBall that inherits from the class Ball. The constructor for this class should provide the height and width of the window, which should be maintained as data fields in the class, rewrite the move method so that the ball moves outside the bound, it automatically reflects its direction. Finally rewrite the BallWorld class to use an instance of BoundedBall rather than ordianary Ball, and elimiante the bounds test in the main program.
    I am having trouble with this and I can not get my code to work, I think I may be going in completly the wrong direction with the code can sombody please provide me with a simple working code for both the BoundedBall and ammended BallWorld class, as this will help me understand whare I am going wrong
    Ball class
    //a generic round colored object that moves
    import java.awt.*;
    public class Ball {
    public Ball (Point lc, int r) {     //constructor for new ball
         //ball centre at point loc, radius rad
         loc = lc;
         rad = r;
    protected Point loc; //position in window
    protected int rad; //radius of ball
    protected double changeInX = 0.0; //horizontal change in ball position in one cycle
    protected double changeInY = 0.0; //vertical change in ball position in one cycle
    protected Color color = Color.blue; //colour of ball
    //methods that set attributes of ball
    public void setColor(Color newColor) {color = newColor;}
    public void setMotion(double dx,double dy)
    {changeInX = dx; changeInY = dy;}
    //methods that access attributes of ball
    public int radius() {return rad;}
    public Point location() {return loc;}
    //methods to reverse motion of the ball
    public void reflectVert(){ changeInY = -changeInY; }
    public void reflectHorz(){ changeInX = -changeInX; }
    //methods to move the ball
    public void moveTo(int x, int y) {loc.move(x,y);}
    public void move(){loc.translate((int)changeInX, (int)changeInY);}
    //method to display ball
    public void paint (Graphics g) {
    g.setColor(color);
    g.fillOval(loc.x-rad, loc.y-rad, 2*rad, 2*rad);
    BallWorld class
    //A bouncing ball animation
    import java.awt.*;          //import the awt package
    import javax.swing.JFrame;     //import the JFrame class from the swing package
    public class BallWorld extends JFrame{
         public static void main (String [] args){
              BallWorld world = new BallWorld(Color.red);
              world.show();
    for(int i = 0; i < 1000; i++) world.run();
    System.exit(0);
         public static final int FrameWidth = 600;
         public static final int FrameHeight = 400;
    private Ball aBall = new Ball(new Point (50,50),20);
         private BallWorld(Color ballColor) {     //constructor for new window
              //resize frame, initialize title
         setSize(FrameWidth, FrameHeight);
         setTitle("Ball World");
    //set colour and motion of ball
         aBall.setColor(ballColor);
         aBall.setMotion(3.0, 6.0);
         public void paint (Graphics g) {
    //first draw the ball
    super.paint(g);
         aBall.paint(g);
    public void run(){
              //move ball slightly
         aBall.move();
    Point pos =aBall.location();
    if ((pos.x < aBall.radius()) ||
    (pos.x > FrameWidth - aBall.radius()))
    aBall.reflectHorz();
    if ((pos.y < aBall.radius()) ||
    (pos.y > FrameHeight - aBall.radius()))
    aBall.reflectVert();
    repaint();
    try{
    Thread.sleep(50);
    } catch(InterruptedException e) {System.exit(0);}

    Here - you can study this :0))import java.awt.*;
    import javax.swing.*;
    public class MovingBall extends JFrame {
       mapPanel map   = new mapPanel();
       public MovingBall() {
          setBounds(10,10,400,300);
          setContentPane(map);
       public class mapPanel extends JPanel {
          Ball ball  = new Ball(this);
          public void paintComponent(Graphics g) {
            super.paintComponent(g);
            ball.paint(g);
    public class Ball extends Thread {
       mapPanel map;
       int x  = 200, y = 20, xi = 1, yi = 1;
    public Ball(mapPanel m) {
       map = m;
       start();
    public synchronized void run(){
       while (true) {
          try{
            sleep(10);
          catch(InterruptedException i){
            System.out.print("Interrupted: ");
          move();
    public void move() {
        map.repaint(x-1,y-1,22,22);
           if (x > map.getWidth()-20 || x < 0)  xi = xi*-1;
           if (y > map.getHeight()-20 || y < 0) yi = yi*-1;
           x = x + xi;
           y = y + yi;
           map.repaint(x-1,y-1,22,22);
        public void paint(Graphics g) {
           Graphics2D g2 = (Graphics2D)g;
           g2.setColor(Color.red);
           g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                               RenderingHints.VALUE_ANTIALIAS_ON);
           g2.fillOval(x,y,20,20);
           g2.dispose();
    public static void main(String[] args) {
       new MovingBall().show();
    }

  • Bouncing Ball without Main Method

    Hi. I needed to reserch on the Internet sample code for a blue bouncing ball which I did below. However, I try coding a main class to start the GUI applet and it's not working. How can I create the appropriate class that would contain the main method to start this particular application which the author did not provide? The actual applet works great and matches the objective of my research (http://www.terrence.com/java/ball.html). The DefaultCloseOperation issues an error so that's why is shown as remarks // below. Then the code in the Ball.java class issues some warning about components being deprecated as shown below. Thank you for your comments and suggestions.
    Compiling 2 source files to C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\build\classes
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:32: warning: [deprecation] size() in java.awt.Component has been deprecated
        size = this.size();
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:93: warning: [deprecation] mouseDown(java.awt.Event,int,int) in java.awt.Component has been deprecated
      public boolean mouseDown(Event e, int x, int y) {
    2 warnings
    import javax.swing.*;
    public class BallMain {
    * @param args the command line arguments
    public static void main(String[] args) {
    Ball ball = new Ball();
    //ball.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    ball.setSize( 500, 175 ); // set frame size
    ball.setVisible( true ); // display frame
    import java.awt.*;*
    *import java.applet.*;
    import java.util.Vector;
    // Java Bouncing Ball
    // Terrence Ma
    // Modified from Java Examples in a Nutshell
    public class Ball extends Applet implements Runnable {
    int x = 150, y = 100, r=50; // Position and radius of the circle
    int dx = 8, dy = 5; // Trajectory of circle
    Dimension size; // The size of the applet
    Image buffer; // The off-screen image for double-buffering
    Graphics bufferGraphics; // A Graphics object for the buffer
    Thread animator; // Thread that performs the animation
    boolean please_stop; // A flag asking animation thread to stop
    /** Set up an off-screen Image for double-buffering */
    public void init() {
    size = this.size();
    buffer = this.createImage(size.width, size.height);
    bufferGraphics = buffer.getGraphics();
    /** Draw the circle at its current position, using double-buffering */
    public void paint(Graphics g) {
    // Draw into the off-screen buffer.
    // Note, we could do even better clipping by setting the clip rectangle
    // of bufferGraphics to be the same as that of g.
    // In Java 1.1: bufferGraphics.setClip(g.getClip());
    bufferGraphics.setColor(Color.white);
    bufferGraphics.fillRect(0, 0, size.width, size.height); // clear the buffer
    bufferGraphics.setColor(Color.blue);
    bufferGraphics.fillOval(x-r, y-r, r*2, r*2); // draw the circle
    // Then copy the off-screen buffer onto the screen
    g.drawImage(buffer, 0, 0, this);
    /** Don't clear the screen; just call paint() immediately
    * It is important to override this method like this for double-buffering */
    public void update(Graphics g) { paint(g); }
    /** The body of the animation thread */
    public void run() {
    while(!please_stop) {
    // Bounce the circle if we've hit an edge.
    if ((x - r + dx < 0) || (x + r + dx > size.width)) dx = -dx;
    if ((y - r + dy < 0) || (y + r + dy > size.height)) dy = -dy;
    // Move the circle.
    x += dx; y += dy;
    // Ask the browser to call our paint() method to redraw the circle
    // at its new position. Tell repaint what portion of the applet needs
    // be redrawn: the rectangle containing the old circle and the
    // the rectangle containing the new circle. These two redraw requests
    // will be merged into a single call to paint()
    repaint(x-r-dx, y-r-dy, 2*r, 2*r); // repaint old position of circle
    repaint(x-r, y-r, 2*r, 2*r); // repaint new position of circle
    // Now pause 50 milliseconds before drawing the circle again.
    try { Thread.sleep(50); } catch (InterruptedException e) { ; }
    animator = null;
    /** Start the animation thread */
    public void start() {
    if (animator == null) {
    please_stop = false;
    animator = new Thread(this);
    animator.start();
    /** Stop the animation thread */
    public void stop() { please_stop = true; }
    /** Allow the user to start and stop the animation by clicking */
    public boolean mouseDown(Event e, int x, int y) {
    if (animator != null) please_stop = true; // if running request a stop
    else start(); // otherwise start it.
    return true;
    }

    FRiveraJr wrote:
    I believe that I stated that this not my code and it was code that I researched.and why the hll should this matter at all? If you want help here from volunteers, your code or not, don't you think that you should take the effort to format it properly?

  • Help with "Exception in thread "Thread-4" java.lang.NullPointerException"

    I am new to Java and I am trying a simple bouncing ball example from Stanford. Here is their simple example that works.
    import acm.program.*;
    import acm.graphics.*;
    import java.awt.*;
    public class BouncingBallWorking extends GraphicsProgram {
    /** sets diameter */
    private static final int DIAM_BALL = 30;
    /** amount y velocity is increased each cycle */
    private static final double GRAVITY = 3;
    /** Animation delay or pause time between ball moves */
    private static final int DELAY = 50;
    /** Initial X and Y location ball*/
    private static final double X_START = DIAM_BALL / 2;
    private static final double Y_START = 100;
    private static final double X_VEL = 3;
    private static final double BOUNCE_REDUCE = 0.9;
    private double xVel = X_VEL;
    private double yVel = 0.0;
    private GOval BallA;
    public void run() {
    setup(X_START,Y_START);
    //         Simulation ends when ball goes off right hand
    //         end of screen
    while (BallA.getX() < getWidth()) {
    moveBall(BallA);
    checkForCollision(BallA);
    pause(DELAY);
    private void setup(double X_coor, double Y_coor) {
    BallA = new GOval(X_coor, Y_coor, DIAM_BALL, DIAM_BALL);
    add(BallA);
    private void moveBall(GOval BallObject) {
    yVel += GRAVITY;
    BallObject.move(xVel,yVel);
    private void checkForCollision(GOval BallObject) {
    if(BallObject.getY() > getHeight() - DIAM_BALL){
    yVel = - yVel * BOUNCE_REDUCE;
    double diff = BallObject.getY() - (getHeight() - DIAM_BALL);
    BallObject.move(0, -2 * diff);
    } Now I am trying to modify "setup" so it I can create several balls. I made a simple modification to "setup" and now I am getting an error.
    "Exception in thread "Thread-4" java.lang.NullPointerException
    at BouncingBallNotWorking.run(BouncingBallNotWorking.java:36)
    at acm.program.Program.runHook(Program.java:1592)
    at acm.program.Program.startRun(Program.java:1581)
    at acm.program.AppletStarter.run(Program.java:1939)
    at java.lang.Thread.run(Unknown Source)"
    Can you describe why I am getting an error? Thanks.
    Here is what I changed.
    Before:
         private void setup(double X_coor, double Y_coor) {
              BallA = new GOval(X_coor, Y_coor, DIAM_BALL, DIAM_BALL);
              add(BallA);
         }After:
         private void setup(double X_coor, double Y_coor, GOval BallObject) {
              BallObject = new GOval(X_coor, Y_coor, DIAM_BALL, DIAM_BALL);
              add(BallObject);
         }Here is the complete code.
    * File:BouncingBall.java
    * This program graphically simulates a bouncing ball
    import acm.program.*;
    import acm.graphics.*;
    import java.awt.*;
    public class BouncingBallNotWorking extends GraphicsProgram {
    /** sets diameter */
    private static final int DIAM_BALL = 30;
    /** amount y velocity is increased each cycle */
    private static final double GRAVITY = 3;
    /** Animation delay or pause time between ball moves */
    private static final int DELAY = 50;
    /** Initial X and Y location ball*/
    private static final double X_START = DIAM_BALL / 2;
    private static final double Y_START = 100;
    private static final double X_VEL = 3;
    private static final double BOUNCE_REDUCE = 0.9;
    private double xVel = X_VEL;
    private double yVel = 0.0;
    private GOval BallA;
    public void run() {
    setup(X_START,Y_START, BallA);
    //         Simulation ends when ball goes off right hand
    //         end of screen
    while (BallA.getX() < getWidth()) {
    moveBall(BallA);
    checkForCollision(BallA);
    pause(DELAY);
    private void setup(double X_coor, double Y_coor, GOval BallObject) {
    BallObject = new GOval(X_coor, Y_coor, DIAM_BALL, DIAM_BALL);
    add(BallObject);
    private void moveBall(GOval BallObject) {
    yVel += GRAVITY;
    BallObject.move(xVel,yVel);
    private void checkForCollision(GOval BallObject) {
    if(BallObject.getY() > getHeight() - DIAM_BALL){
    yVel = - yVel * BOUNCE_REDUCE;
    double diff = BallObject.getY() - (getHeight() - DIAM_BALL);
    BallObject.move(0, -2 * diff);
    } Edited by: TiredRyan on Mar 19, 2010 1:47 AM

    TiredRyan wrote:
    That is great! Thanks. I've got two question though.
    1.) Now I want to have 100 bouncing balls. Is the best way to achieve this is through an array of GOvals? I haven't gotten to the lecture on arrays on Stanford's ITunesU site yet so I am not sure what is possible with what I know now.An array would work, or a List. But it doesn't matter much in this case.
    2.) Are references being passed by value only applicable to Java or is that common to object-oriented programming? Also is there a way to force Java to pass in "BallA" instead of the value "null"?I can't say about all OO languages as a whole, but at least C++ can pass by reference.
    And no, there's no way to pass a reference to the BallA variable, so the method would initialize it and it wouldn't be null anymore.
    When you call the method with your BallA variable, the value of the variable is examined and it's passed to the method. So you can't pass the name of a variable where you'd want to store some object you created in the method.
    But you don't need to either, so there's no harm done.

Maybe you are looking for

  • Which universal dock adapter and connection

    Hi, I like to find out which dock adapter is right for the ipod video 30GB? and does the new ipod accept USB 2.0 connection only? I tried firewire and it doesn't accept the connection, thanks for reading, Tom

  • AR Customer Aging - Calculations

    Hi I wanted to customize the customer aging report in AR, i was using the ORACLE API to calculate the aging, the API does not take care of the receipts, and reverse amout, I ended up in defining a new query for calcuating the receipts and reversal am

  • Can't drive mapping with jre1.4.2_11

    I need to drive mapping with jre1.4.2_11 in Windows applications but I can't. If you change the file java.policy with all permission then the drive mapping works properly. But if you want to add permission only for the drive mapping?? Anyone knows ab

  • Mac os x 10.7.5 and gmail

    I have 3 email accounts: Roadrunner, Gmail and Apple.  Only my Gmail account has freaked. 1)  Some of my incoming emails go directly to Trash, others come to the Inbox - ???? 2)  My sent messages appear in the Trash and in the Sent folder. This is on

  • Fetch - Single

    Hi, I have in Rmk(DOC-DCT-KCo , for eg., 0012563-OP-00605) field in F0911. To split up RMk field i get these DOC,DCT and KCo and again i need to apply with F0911 to get their MCu, OBJ, SUB. I used fetch single but it not works. Could anybody help on