Need help making ball move and bounce off of sides of JPanel

I'm currently working on a program that creates a ball of random color. I'm trying to make the ball move around the JPanel it is contained in and if it hits a wall it should bounce off of it. I have been able to draw the ball and make it fill with a random color. However, I cannot get it to move around and bounce off the walls. Below is the code for the class that creates the ball. Should I possible be using multithreads? As part of the project requirements I will need to utilizes threads and include a runnable. However, I wanted to get it working with one first and than add to it as the final product needs to include new balls being added with each mouse click. Any help would be appreciated.
Thanks
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Ball extends JPanel{
    Graphics g;
    int rval; // red color value
    int gval; // green color value
    int bval; // blue color value
    private int x = 1;
    private int y = 1;
    private int dx = 2;
    private int dy = 2;
    public void paintComponent(Graphics g){
        for(int counter = 0; counter < 100; counter++){
            // randomly chooses red, green and blue values changing color of ball each time
            rval = (int)Math.floor(Math.random() * 256);
            gval = (int)Math.floor(Math.random() * 256);
            bval = (int)Math.floor(Math.random() * 256);
            super.paintComponent(g);
            g.drawOval(0,0,30,30);   // draws circle
            g.setColor(new Color(rval,gval,bval)); // takes random numbers from above and creates RGB color value to be displayed
            g.fillOval(x,y,30,30); // adds color to circle
            move(g);
    } // end paintComponent
    public void move(Graphics g){
        g.fillOval(x, y, 30, 30);
        x += dx;
        y += dy;
        if(x < 0){
            x = 0;
            dx = -dx;
        if (x + 30 >= 400) {
            x = 400 - 30;
            dx = -dx;
        if (y < 0) {
            y = 0;
            dy = -dy;
        if (y + 30 >= 400) {
            y = 400 - 30;
            dy = -dy;
        g.fillOval(x, y, 30, 30);
        g.dispose();
} // end Ball class

Create a bounding box using the size of the panel. Each time you move the ball, check that it's still inside the box. If it isn't, then change it's direction. You know where the ball is, (x, y), so just compare those values to the boundary values.

Similar Messages

  • Need help with rented movies and Apple TV

    I rented two movies from the iTunes Store from my laptop rather than my Apple TV. I cannot get the rented movies to show up on my Apple TV. I've tried to "move" the two movies from my laptop to Apple TV via the Apple TV tab in iTunes where it shows both movies under a "Rented Movies" section and gives me the option to "move" each one to my Apple TV, but when I click on each movie to move it to the Apple TV and then hit "Apply," nothing happens (at least as far as I can tell). Is there someplace special I need to find rented movies using my Apple TV remote? I clearly need help, please!

    Hi Winston,
    I have purchased the third generation of Apple TV but have not installed it yet, so I am still using my second generation Apple TV, for which I posed this question. Is the answer different when using Apple TV II?

  • Help - making a movie and the file is jumpy

    I'm making a slideshow to show a group of 50 students tonight. I've never had this issue with iMovie before. I have iMovie '11 and OS Lion. The file is like it has scratch marks that appear at various times, whether it's a transition or just displaying a picture.
    It's not the end of the world because the file will still play, but it's noticeable that the file is jumpy/glitchy (sorry I don't have a better technical way of describing this).
    I have exporting as a quicktime file, it's still there, watched it on other macs and pcs, still there.
    Any help would be great. Need to show this tonight!

    What do you mean missing?
    It downloaded?  It was on your computer?  It then disappeared?
    In the U.S. look under Quick Links and Click Purchased

  • I need help making Adobe Edge animation appear correctly on iphones, ipads and android phones.

    I need help making Adobe Edge animation appear correctly on iphones, ipads and android phones. It currently looks fine on desktops and androids. I am using wordpress with a responsive theme (Canvas). I will need you to document The url is http://adamhtc.org.s183459.gridserver.com.

    Thanks George, interesting thought.  I looked on Adobe's site and they "advertise" fillable forms for the iPhone and Android markets, but on the Windows Phone tab, that is mysteriously missing.  lol    Maybe it will come later?   Meanwhile, I'll google to see if there are any PDF viewers that can handle it now.   Thanks for the reply.  :-)

  • My grandma is a new apple user and she needs help making an apple account.

    my grandma is a new apple user and she needs help making an apple account.

    She should call Apple support or visit the Genius Bar at an Apple store (make an appointment first at http://apple.com/retail). They will walk her through the process.

  • I need help, yesterday I installed and reinstalled the Yosemite system and take long to turn on my laptop, the bar takes to fill, and I'm worried. Can you help? thank

    I need help, yesterday I installed and reinstalled the Yosemite system and take long to turn on my laptop, the bar takes to fill, and I'm worried.
    Can you help? thank

    revert back to Maverick that is what I had to finally do. This was the worst upgrade I have ever seen. Hopefully you have Time Machine backup and can revert back. It was pretty painless except for a few issues. I will wait until Apple gets their stuff together on this upgrade or may never will.

  • Need help with Blog, Wiki and Gallery

    Hi Team,
    Need help with Blog, Wiki and Gallery startup. I have newly started visiting forums and quite interested to contribute towards these areas also.
    Please help.
    Thanks,
    Santosh Singh
    Santosh Singh

    Hello Santhosh,
    Blog is for Microsoft employees only. However, you can contribute towards WIKI and GALLERY using the below links.
    http://social.technet.microsoft.com/wiki/
    http://gallery.technet.microsoft.com/

  • After making a movie and wanting to burn a DVD, I go for iDVD in the 'DEEL'  menu. Then I get the question ' where is iDVD? What is the problem?

    After making a movie and wanting to burn a DVD, I go for iDVD in the 'DEEL'  menu. After couple of seconds I get the question ' where is iDVD?
    What is the problem? I cannot find iDVD in the programs map.
    regards Tonl

    The current Apple thinking is that the entire world has access to fast broadband and wants to distribute home movies to friends and relatives via download (iCloud) rather than mailing them a DVD. The fact that nothing could be further from the truth has so far had no effect on this policy. If you scream and shout loudly enough down the phone Apple may send you a free copy of iDVD. That worked for some, but is now said to have been withdrawn by Apple. Also, you can complain bitterly here, perhaps suggesting that Apple could have provided a choice between using iCloud and burning DVDs:
    http://www.apple.com/feedback/
    Whilst Macs with a Superdrive continue to be able to burn video DVDs, the software for so doing, iDVD, is no longer included in the iLife bundle that comes with OS 10.7 Lion (which also omitted iWeb) or will come with OS 10.8 Mountain Lion. And it is no longer included in the iLife 11 from the online Apple Store: http://www.apple.com/ilife/. Your only solution is to look on Amazon or eBay and try to get an older version that includes iDVD.
    However, the vastly more expensive FCPX can burn a DVD without iDVD or DVD Studio Pro involvement, but lack the themes etc of iDVD.

  • Need help FLASH not launching and not uninstalling "licensing for this product has stopped working".

    Need help FLASH not launching and not uninstalling "licensing for this product has stopped working" and " you can only install one adobe product at a time please complete the other installation"  Flash was working absolutely fine before, I have no idea why this happened.

    I am having similar problem.  Can't open any of CS3 programs after trying to download Dreamweaver Trial, which wouldn't work because "couldn't remove DLM extention" error message.  So now I can not run Illustrator, Photoshop, or even Adobe Reader.  These are properly licensed for about a year. I get "License for product has stopped working".  Have 2 pending cases open with Adobe support (one for Dreamweaver trial, one for license problem) since 8/3 with NO ANSWERS - It says answers within 1-3 business days.  Was on phone support hold today for over 3 hours before line went dead with no help.  What is up with adobe support?  Can anyone help?

  • HT5622 I need help finding a movie that I downloaded, can anyone help me with this?

    Hello, I need help finding a movie that I downloaded, can anyone help me with this?

    If you downloaded it to your iTunes library it will be in the Movies folder.  If you downloaded it to an iOS device you will find it in the Videos app.  This explains how to redownload previously purchased videos (available in some locations as long as the studio permits it): http://support.apple.com/kb/PH12283.

  • I need help importing navigation bars and rollover buttons from fireworks?

    I need help importing navigation bars and rollover buttons from fireworks, drop down menus and rollover states won't work!
    Thanks

    In my experience, the code created by graphics apps is less than satisfactory. And image based menus are very awkward for several reasons. 
    #1 If you decide to change your menu later, you must go back to your graphics app and re-craft the whole thing.  After 2-3 times of this, it gets old in a hurry.
    #2 Image based menus cannot be "seen" by search engines, screen readers and language translators.
    #3 CSS styled text menus are better for your site's visibility, accessibility and they are a snap to edit in Dreamweaver.
    That said, if you're still married to image based menus, use Fireworks to create images only. Use Dreamweaver's Image Rollover Behaviors to create your rollover scripts.
    Nancy O.

  • I need help understanding export options and optimizing for web

    I have been using FCP X for a short while now and have a pretty good grasp on the editing capabilities. What I'm having a horrible time figuring out is the export/share options. The videos I create are typically approximately 1 minute in length and get posted to a web site (we have our own CMS and video player so I'm not using YouTube or Vimeo or anything like that). In order to post them I need them to be MP4s and then I have to create .webm and .ogv files. The source material I work with is generally great, high quality stuff, so I end up with very large output files from the initial FCP share master file options.
    When I use MPEG Streamclip to make my MP4s I end up with files that are still quite large and I can't seem to ever get the file size manageable without losing tons of quality. I do not have Compressor, though if that will solve my problem I will put in for the expense of it. What I'm trying to understand is what sorts of settings I should be trying out to get my file sizes to be manageable without completely compromising my quality. And I know this can be done, because the company I work for pays for a great quantity of video work each year (from an outside production firm) and the clips provided are beautiful in quality and small in file size -- for example, I recently worked on a video and got it into the 40MB range before quality went to crap, working off the same material the production company we do work with had theirs down into the teens and looking beautiful!
    To throw an even greater wrench in the works, I am working off a mac. But when my boss, on a pc, saves the mp4s I create (raw files -- not what is posted to the web) locally on his machine and views them from there the sound is always off a tad and the people in the videos look like they're lip synching.
    Any advice on either of these is MUCH appreciated. I've been trying to figure this out properly for months, and only today decided to stop seeing if someone else had the same question and just post my own.
    Bronwyn

    Thank you Karsten, this was helpful I have utilized the Quality slider and the frame size options before though with limited results. I've never messed with the Limit Date Rate option as I don't know what I'm doing with it, I see you put 5Mbps. Is that a typical setting that I could use?
    Using stream info, here's info on my original source file:
    Stream: Charles_0023_2.mov
    Duration: 0:00:51
    Data Size: 96.51 MB
    Bit Rate: 15.77 Mbps
    Video Tracks:
    H.264, 1920 × 1080, 29.97 fps, 15.64 Mbps
    Audio Tracks:
    MPEG-4 Audio stereo, 48 kHz, 127 kbps
    Stream Files:
    Charles_0023_2.mov (96.51 MB)
    As a comparison, here's the info on a similar clip that the company we sometimes use created:
    Stream: Charles_0019_4.mp4
    Duration: 0:00:49
    Data Size: 4.66 MB
    Bit Rate: 0.80 Mbps
    Video Tracks:
    JVT/AVC Coding, 710 × 400, 29.97 fps, 635 kbps
    Audio Tracks:
    MPEG-4 Audio stereo, 48 kHz, 162 kbps
    Stream Files:
    Charles_0019_4.mp4 (4.66 MB)
    I'm fine with bringing the frame size down some and modifying the limit data rate, but sometimes I feel like I'm forcing my video into something it's not and the quality suffers -- this is where my understanding of video work breaks down LOL. Any suggestions of how I can get my .mov into something like the the .mp4 above?
    Also have you had any experience with mp4s not playing back properly on pcs?
    Again, thank you!
    Bronwyn

  • Trying to create a movie clip that Bounces off four sides of the stage

    using the syntax below I have created a movie clip called 'BALL' that bounces off from the left "x"  and moves to the right side of the stage 'x.520' and bounces back to the start "x".
    HOW DO I CREATE A MOVIE CLIP THAT BOUNCES FOUR SIDES OF THE STAGE AND STOPS ON THE FOURTH BOUNCE??
    var ballTween:Tween = new Tween(ball, "x", Bounce.easeInOut, ball.x,520, 5, true);
    ballTween.addEventListener(TweenEvent.MOTION_FINISH,tweenFinishedF);
    function tweenFinishedF(e:TweenEvent):void{
    new Tween(ball,"x",Bounce.easeOut,ball.x,0,5,true);

    Here is a simplest way to do that. This code doesn't use your ball but draws it dynamically. If you want to use your ball instance - replace relevant lines.
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.geom.Rectangle;
    var ball:Shape;
    // speed, naturally
    var speed:Number = 7;
    // velocity along x
    var vx:Number = speed;
    // vlocity along y
    var vy:Number = speed;
    // area within which ball may move
    var moveArea:Rectangle;
    // radius of ball circle shape
    var ballRadius:Number = 20;
    init();
    function init():void
        moveArea = new Rectangle(ballRadius, ballRadius, stage.stageWidth - ballRadius, stage.stageHeight - ballRadius);
        drawBall();
        addEventListener(Event.ENTER_FRAME, moveBall);
    function moveBall(e:Event):void
        // change direction if ball moves out of allowed rectangle
        if (ball.x < moveArea.x)
            vx = speed;
        else if (ball.x > moveArea.width)
            vx = -speed;
        if (ball.y < moveArea.y)
            vy = speed;
        else if (ball.y > moveArea.height)
            vy = -speed;
        ball.x += vx;
        ball.y += vy;
    function drawBall():void
        ball = new Shape();
        ball.graphics.beginFill(0xFF0000);
        ball.graphics.drawCircle(0, 0, ballRadius);
        ball.x = moveArea.x + Math.random() * moveArea.width;
        ball.y = moveArea.y + Math.random() * moveArea.height;
        addChild(ball);
    Message was edited by: Andrei1

  • Need help with Airport Express and so on.

    Ok so my main problem before getting into what I need help with here is that our MacBooks and now my iPhone 6 plus isn't staying online. Keep getting booted off and then I either have to select the network again or it will eventually go back on. If anyone has a solution or so please feel free to answer that as well. I'm running on Roadrunner with a Netgear 600 wireless router and a motorola modem. Both of which I'll leave the link to below for a better look.
    My Main Question: So I'm looking at a new wireless router mainly and possibly a new modem. I know Apple products are trustworthy but how good is the Airport Express and other Airport products. Also what is the Maximum speed and Maximum data speed for the cheapest express station and if anyone knows the speeds of the other devices it would be greatly appreciated.

    DSL Router to Netgear 5-port Switch and I used the switch to connect to Airport Extreme, TV, Blue-Ray DVD player and DirecTV Receiver.
    The AirPort Extreme base station (AEBS) is a router so it will do what you need.
    You need to reconfigure your setup. Connect the WAN port of the AEBS to the DSL router. Then connect the Netgear switch to one of the LAN ports on the AEBS. The AEBS will properly share the connection.

  • FCP Novice needs help with video quality and FCP 5!!

    Hi,
    I have a real problme that I cannot seem to fix. I think its because I am doing something really wrong!
    I have a Sony HC42E MiniDV Camcorder which by default records video in full widescreen. I recorded several tapes this way and have now begun trying to edit them in FCP 5.04 (Tiger 10.4.6). Whenever I log and capture my clips they appear to be fuzzzy and unclear on the Mac monitor whilst being totally crisp and sharp on the camcorder viewfinder. I tried capturing using the DV PAL 48Khz Anamorphic Preset which keeps everything the right size (the final output needs to be true widescreen and not with black bars added) but the resulting video on screen is blurry and bitty. I then tried capturing using the DV PAL 720 x 576 normal preset and the video is a little clearer on the screen (for both presets I have chosen lower field dominance) but when I play back it plays back in widescreen on the mac canvas window but at 4:3 on the camera's viewfinder.
    I then assumed that maybe this is just becuase the mac screen (CRT by the way) doesn't use fields. So I exported the sequence as a QT movie using DV PAL 16:9 and used quicktime (OS9 Classic - my compressor has never worked because of the dreaded "unable to connect to baackground process" problem which I've never managed to correct) to convert it to MPEG2. When I import this as an asset into DVD Studio pro 4 and set the track size to 16:9 it comes through at the right aspect ratio. However it looks blurry on screen. Thinking that this will be fine on a TV I burned the disc - inserted it into my DVD player (a good one!) and watched it on my new 32" widescreen TV (a good one!) and the picture qualitty is poor. Its so much blurrier and bittier than the original footage looks when played through the camcorder's viewfinder!
    The final footaage looks like an old VHS recording that's a year or two old!
    Does anyone know how I can capture my footage in FCP with the maximum quality, edit it without quality loss and the export it for DVD again without such significant quality loss whilst all the time keeping it at proper 16:9 widescreen?
    Is there some presets I should be working to?
    I'm tearing my hair out! Help!

    Hi Guys,
    thanx for your replies.
    here's the latest:
    Brian, I followed your instructions and the DVD burned successfully. However the video quality of the dvd when viewed on my TV ('ve tried on all 3 of my tvs now) is still a lot poorer than the quicktime movie that was imported into DVDSP4. When I play the original QT Movie on my Mac CRT monitor it looks a little blurry and grainy because I guess its non interlaced however when viewed on an external Video monitor it looks great - very sharp.
    When I view the burned DVD on my television the picture quality looks like the non interlaced version of the original QT Movie that appeared on my Mac CRT and not the sharp interlaced (lower field) version that appeared on my external video monitor.
    Its almost like taking a sharp jpeg into Photoshop and applying a gaussian blur of about 0.3 followed by jepg compression compressing it down to 5% quality!
    I'm totally mystified. Can the conversion to Mpeg2 be removing all interlacing so that you get the less sharp computer monitor look? I just want the video on my final DVDs to be as good as the original source footage! I appreciate that along the way there might be loss of some quality but surely not that much?
    Does this make sense to you guys or am I still doing something very wrong?
    Robert: I have tried setting all manner of drives including a fresh external firewire HD with nothing on it (clean out of the box) but it doesn't seem to help.
    Brian: I tried the no network suggestion a few months back but I'm not sure if I got it right. At the moment I have broadband through an external speedtouch usb modem and am also connected (occasionally although not for the last 3 months) via a crossover cable to my PCs ethernet card. When I last tried the No Network solution I had immense trouble getting my internet to work again! Can you please help me by directing me to the best ay to do this while protecting my internet settings?
    any more help guys would be greatfully appreciated.

Maybe you are looking for

  • Clob datatype and JDBC

    JDBC does not support CLOB, as i figured out the hard way, or is the version of JDBC that i have that is not supporting it. Can someone advise me on how do i get around this problem? Database that i connecting to has clob types. Alex null

  • PO Report by PO creator's name

    Hello! Is there any way (other than the Document Overview Method and the EKKO Database Table Method) wherein a PO report can be generated along with the PO creators name. Thanks in advance. Riju.

  • Receive error 'Adobe Reader 9.3 has stopped working'

    Good Day Everyone. Having difficulty opening a .pdf file.  Have used Adobe Reader 9.0 and 9.3 but without any success. Didn't used to have any problem opening pdfs but over last few months have experienced severql difficulties, which have resulted in

  • I-phone 2.0 update - lost all contacts

    This a.m. did the 2.0 update and lost all contacts. Calender good, photos good, notes good, mail good. Did not have on PC but part of download said "backing up information" WHERE? Did 2nd I-phone right after, before checking the first one, and that d

  • Move wildcard SSL cert from 10.7 to 10.6 server

    I purchased and configured a wildcard cert (*.example.com) on my 10.7 server. I now want to import this cert onto my 10.6 servers (all using the same domain) and I can't seem to get it to work. I exported both the cert and the private key file from t