Bouncing Ball Just Suddenly Stops Mid Bounce

I have a application where each time you click the add ball button a new randomly colored ball is added to the jpanel. It works fine except that the balls suddenly stop at the same spot. I want them to continue to bounce for a longer period of time instead of like 8 bounces. It was going around withoutstopping prior to my getting the add new ball part working. I cannot seem to figure out what I did wrong. Also curious if anyone new of a tip as to how to get the balls to disappear once a button is clicked or their cycle runs out. Below is my code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class BounceBall{
    public static void main(String[] args) {
        JFrame frame = new BounceFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS  E);
        frame.setVisible(true);
class BounceFrame extends JFrame {
    private BallCanvas canvas;
    public static final int WIDTH = 450;
    public static final int HEIGHT = 350;
    public BounceFrame() {
        setSize(WIDTH, HEIGHT);
        setTitle("BounceThread");
        Container contentPane = getContentPane();
        canvas = new BallCanvas();
        contentPane.add(canvas, BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel();
        addButton(buttonPanel, "Add Ball",
                new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                addBall();
        addButton(buttonPanel, "Exit",
                new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                System.exit(0);
class BallThread extends Thread {
    private BouncingBall b;
    public BallThread(BouncingBall aBall) { b = aBall; }
    public void run() {
        try {
            for (int i = 1; i <= 1000; i++) {
                b.move();
                sleep(5);
        } catch (InterruptedException exception) {
class BallCanvas extends JPanel {
    private ArrayList balls = new ArrayList();
    public void add(BouncingBall b) {
        balls.add(b);
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        for (int i = 0; i < balls.size(); i++) {
            BouncingBall b = (BouncingBall)balls.get(i);
            b.draw(g2);
class BouncingBall {
    private Component canvas;
    private static final int XSIZE = 15;
    private static final int YSIZE = 15;
    private int x = 0;
    private int y = 0;
    private int dx = 2;
    private int dy = 2;
    public BouncingBall(Component c) { canvas = c; }
    Color color = getColor();
    public void draw(Graphics2D g2) {
        g2.setColor(color);
        g2.fillOval(x,y,30,30);   // adds color to circle
        g2.drawOval(x,y,30,30);   // draws circle
    public void move() {
        x += dx;
        y += dy;
        if (x < 0) {
            x = 0;
            dx = -dx;
        if (x + XSIZE >= canvas.getWidth()) {
            x = canvas.getWidth() - XSIZE;
            dx = -dx;
        if (y < 0) {
            y = 0;
            dy = -dy;
        if (y + YSIZE >= canvas.getHeight()) {
            y = canvas.getHeight() - YSIZE;
            dy = -dy;
        canvas.repaint();
    private Color getColor() {
        int rval = (int)Math.floor(Math.random() * 256);
        int gval = (int)Math.floor(Math.random() * 256);
        int bval = (int)Math.floor(Math.random() * 256);
        return new Color(rval, gval, bval);
    }Edited by: wnymetsfan on Dec 2, 2007 2:01 PM

wnymetsfan wrote:
Actually it is comiliable as I ran it numerous times today asI tried to fix it. No, it does not compile. Besides the obvious error:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS  E);, a large part of the BounceFrame class seems to be missing: I don't see a addButton(...) anywhere.
I posted here since it says new to java which I am. I also have posted here before with questions relatedto swing and 2D elements like graphs and no one else had an issue. It's not prohibited to post it here, but in the 2d forums, there are more people who know what they're talking about when it comes to 2D animations.
Thanks for the links to the other forums I will post there. Sorry to bother you guys as I was not aware that New to Java meant only if it doesn't involves things like swing and 2DIt's not a bother: I merely said it for you to get help sooner.

Similar Messages

  • TS1286 MY MUSIC WILL PLAY THROUGH THE IPOD BUT NOT THROUGH ANY DOCKING STATION SPEAKERS. IT USED TO, BUT JUST SUDDENLY STOPPED.

    My music will play through my ipod speakers, but it won't work through docking station speakers. It used to but then just suddenly stopped. Can anyone help??

    I just had this problem tonight and here is what worked:  Go to Settings; General; Software Update; and update to the new iOS:  6.0.1.  It worked for me, hope it works for you!

  • HT1430 My iPad isn't getting connection to internet.  It just suddenly stopped!  It says it is connected to WiFi but it just keeps spinning and nothing will come up.  Have tried rebooting my router and iPad (my other computer is connected just fine).

    My iPad isn't getting connection to internet.  It just suddenly stopped!  It says it is connected to WiFi but it just keeps spinning and nothing will come up.  Have tried rebooting my router and iPad (my other computer is connected just fine).

    Try turning WiFi off on the iPad, then reset it again, turn WiFi on again and join your network again if necessary. Or go to Settings>WiFi>Your network name>Forget this network. Reset your iPad and then join your network again. Or - settings>General>Reset>Reset network settings. Reset the iPad, then try to join your network again.

  • HT204368 My Bluetooth just suddenly stopped working with my vehicles factory system. It's worked for almost a year with no issues. My wife's phone will easily paid with the vehicle,so nothing has changed with the vehicle. What gives apple?

    Why would my bluetooth suddenly stop working?

    I have had non-Apple Bluetooth devices simply stop communicating after being paired with a device for a year or longer with no apparent reason. The solution was simply to pair the device again.
    An explanation is likely to be elusive, resulting only in manufacturers of the devices blaming each other for deficiencies either real or imagined.

  • My imac has just suddenly stopped connecting to the net

    My mac just radomly stopped connecting to the internet last week and i cant get it to reconnect again. All the other devices in my house connect perfectly. i use an O2 home hub and have had no problems for a year with this so im guessing its the mac. my girlfriend recently bought a printer and plugged it in next to the mac but it isnt connected, is there any chance this could be blocking the wireless signal? thanks mike

    Hi Mike...
    Try turning off the router for about 5 minutes, then turn it back on then restart the Mac.
    If the printer isn't setup for printing with the Mac, I doubt that's the problem.

  • My 4th row of keys on my mac book pro just suddenly stopped working and i have no idea why? Can someone help me fix them?

    My 4th row of keys on my mac book pro just stopped working all of a sudden,does anyone know how to fix it?

    Which model MBP do you have?
    If you are still under warranty and/or have AppleCare, call them.  Let them deal w/it. 
    Out of warranty DIY instructions can be found on... 
    iFixit 
    TakeItApart
    Search YouTube for Macbook Pro “How To” tutorials.
    How to replace keys on an Apple MacBook Pro SILVER Keyboard
    https://www.youtube.com/watch?v=JjRTQIfVTgU

  • Sound just suddenly stopped on my laptop

    I am on my laptop and all of a sudden there is no sound. I checked the volume, it is on, I tried turning the laptop on and off and that still didn't help.
    I am unsure of what to do, I went into control panel, clicked on system and security, find and fix problems and followed the instructions, that did not work. Said troubleshooting couldn't identify the problem. I have no idea what to do next. It was working while I was listening to a youtube video, then it just stopped.
    Any advice for a not-so-savvy computer person.
    Thanks,
    LI Roe
    I have a HP Pavilion dv7-6c95dx Entertainment PC
    Product a6x02ua#aba   
    Windows 7 Home Premium 64 bit - Service Pack 1
    This question was solved.
    View Solution.

    Hello LlRoe,
    I see that you are having problems with the sound on your HP computer. I have some suggestions that may help with this issue.
    Here is a link to some troubleshooting steps for sound issues on your computer. It includes some steps you already tried but continue past those and try the other steps including reinstalling the sound drivers.
    ↙-----------How do I give Kudos?| How do I mark a post as Solved? ----------------↓

  • HT1430 My mail service with Yahoo just suddenly stopped working.  Can't access Yahoo.  Restart did not help.  Help

    My Yahoo mail service stopped working on my Iphone.  Works fine from my PC.  Help  Did restart but no help.

    Hello Bad Don,
    Thank you for using Apple Support Communities!
    I would recommend performing the troubleshooting steps in this article named iOS: Unable to send or receive email found here http://support.apple.com/kb/ts3899
    Try an alternative Internet connection.
    If your email is provided by your Internet provider, try connecting from the home network.
    If your iOS device has an active cellular data plan, try to disable Wi-Fi:  Tap Settings > Wi-Fi and turn off Wi-Fi.
    If not, try a different Wi-Fi network.
    Log in to your email provider's website to ensure that the account is active and the password is correct.
    Delete the account from Settings > Mail, Contacts, Calendars and then add the email account again on the iOS device.
    If you're still unable to send or receive email, contact your email provider and verify the account settings are correct. You will need to gather this information (PDF).
    If none of that resolves the issue, I would backup and restore the device with iTunes.
    iOS: How to back up and restore your content
    http://support.apple.com/kb/HT1766
    All the best,
    Sterling

  • Music suddenly stops mid-song

    Lately, my iPod nano (gen 4) will stop in the middle of a song. I'll pick it up and advance to the next song and it will happen again. But here are the really odd things: first, only music stops, not pod casts or audio books; and second, so far this has happened only in my car (plugged into the audio port), not when it's plugged into exercise equipment. Does anyone have any ideas as to what might be going on? Is the iPod nearing its end date?

    You will probably need to quit iTunes when this happens since it may still have an active reference to a file on the iPod.
    If you ever get a message telling you a disk is in use when you eject it, it is probably because a file on the disk is still open by an application. The best thing to do in this situation is quitting the programs that you think that used a file on that disk. This may be necessary because an application forgot to close a file.

  • Dvi port just suddenly stopped working

    i got a destop hp pavilion s3621uk
    with monitor ViewSonic vE510b 
    as always i use the dvi to vga adaptor which came along with the with the pc when i bought it 
    then one day when it suddenly cannot not display on the screen
    This question was solved.
    View Solution.

    When you install a video card that has DVI \ VGA outputs they will work, but not the video outputs at the rear of the motherboard. The BIOS will disable the onboard video. you can check it in the BIOS, but I don't expect you will see any video settings.
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • I have songs on iTunes that seem to have corrupted files with time.  The songs play for a while then suddenly stop mid-song and iTunes goes to the next song.  On my iPod the playback pauses for a few seconds then picks up again.

    Some of these songs were purchased via iTunes.  I would like to download them again but the Download buttons are grayed out when I bring up the purchased songs listing.  Any help appreciated.  Is there any way to quickly get a file integrity check done?
    Kerry

    Depending upon what country that you are in (music can't be re-downloaded in all countries) then try deleting those incomplete tracks from your iTunes library and redownload them (if they are still in your country's store) via the Purchased link under Quicklinks on the right-hand side of the iTunes store home page on your computer's iTunes. Or delete them and copy them back (File > Add To Library) from your backup of your downloads/library.

  • I can no longer attach files to email. Just suddenly stopped.

    I haven't installed an update or any new files. I was able to attach files yesterday but today, for some reason, they won't attach. I select the paperclip but nothing happens. No error message, nothing behind the open pane. I've rest my IE settings to default (even though I don't use it) but that didn't help. I've off/on the PC and that didn't work either. I've run my antivirus software and it finds nothing wrong.

    Could you check your pop-up setting for google.com? Here's how:
    While you have the compose window on the screen, click the padlock in the address bar.
    * If the pop-up permission is listed there as Block, try changing it to Allow.
    * If the pop-up permission is not listed there, click More Information to launch the Page Info dialog, then click Permissions in the top bar. Scroll down to "Open pop-up windows", uncheck the box for "Set default" then click Allow and close the dialog.
    Then try the paper clip again. Success?
    Unfortunately, that is "Google-wide" and not limited to mail, so... other pop-ups are possible that you've never noticed before.

  • F-4480 printer just suddenly stopped responding.

    Had been printing a series of letters when pop-up stated printer was low on color.
    I replaced the color cartridge and printer hasn't worked since.

    Can you provide some additional details?
    - When you say the printer hasn't worked since, what does the printer do?  Do you get lights coming on, on the printer?  Do you get an error message?
    - Was it a new HP cartridge or a refill?
    Thanks
    Say Thanks by clicking the Kudos thumbs up. Please mark the post that solves your problem as an Accepted Solution so other forum users can utilize the solution.
    I am an HP employee.

  • Sudden stops in Logic when a new track starts playing

    This problem has dogged me for years, with three different Macs, loads of different OS versions, loads of different interfaces and loads of different Logic Pro versions. I have upgraded from 7 to 8 and it's still happening, in fact worse in 8 than in 7: A song will occasionally just suddenly stop, usually exactly where a track starts. So for example if I have a track with data starting at bar 17, Logic sometimes, randomly, simply stops when it reaches bar 17. The track can be Audio recording, or midi playing a Logic or AU virtual instrument - makes no difference. If I reset to the beginning and start again it will always play past the problem point no trouble, every single time. Occasionally though it will stop later in the song where another track starts. It makes no difference how much processing is going on. I have songs with only four bounced (not frozen) audio tracks and a bit of external midi, where the CPU bars on my Macbook Pro don't even move, and yet it can stop, not always, but sometimes. I use Logic Pro live on stage and it's a killer I can tell you. Anyone else suffering the same problem? I'm thinking of abandoning Logic and going to Ableton!

    I'm glad you said that. I've been using Logic since it came into existance, and I've had this kind of behavious, often accompanied by a message saying Midi and audio have gone out of sync, since Logic Audio came out. I'm no Mac guru, but I do know my way around with the OS, and with audio generally, and I'm sure I'm not doing anything silly, but this problem makes it very dangerous to use Logic in a live situation. The Pet Shop Boys tour with a similar rig to mine, and I know they have exactly the same problem. They're lucky enough to be able to run two rigs in parallel, but even so, it must be scary not knowing when Logic will suddenly decide to stop in the middle of a song! If anyone has had this and cured it, please, please tell me what you did.

  • Printing Suddenly Stopped

    My Canon i9900 just suddenly stopped printing from any computer in my home network. My MBP just started displaying all prior print jobs in the print queue, even those completed going back almost a full year. There was no way to clear the queue, so I reset the print settings, clearing out the printer entirely, and trashing the printer from the library. While I'm working through the problem from the one computer, I can't print from any other computer to this printer. Do I need to reset printing system on every computer? Seems odd that everything wouldlock up and cause all computers to need to be reset.

    Just an update - I was able to print from a Windows computer hooked up to the same printer, so I know the printer is still functioning properly. Airport device also appears to be working properly. Next will check USB cable - after that I'm at a bit of a loss.

Maybe you are looking for

  • Including JavaScript in a .js File Referenced by the Page Template

    http://download-uk.oracle.com/docs/cd/B31036_01/doc/appdev.22/b28839/javascript.htm#BCEHEFGF Hi trying to implament Patrick's Library In the above it gives you the following to put into the template header <script src="http://myserver.myport/my_image

  • Vendor payment in another currency

    Please clarify the following: I have posted a vendor invoice in USD. Is it possible to pay the vendor in another currency ?

  • Why on my screen is the text not all showing, it is overlapped by other txt or graphics?

    on some windows the graphics are out of place and over lap text, in other cases text overlaps text as if the entire page is not showing as it should, it makes reading the window, page impossible.

  • Common distributions channels

    Hi everybody: I want to use the functionality of common distributions channels only for the creation of customer's master data. I want to preserve the update of sales area to the material’s master data because the same material in the same company co

  • Advances received from the customer

    Hi, This is regarding the receipt of advance from the customer against a sales order.As per the terms of payment, on receipt of the confirmation of the order the customer has agreed to pay 10% of the sales order value as the advance. *In case if the