Help making a ball move

Hi all.
I'm trying to make a ball (in a panel) move left and right when I press down left and right keys, but I cant seem to get it working. Can someone please advise me where I might be getting it wrong.
Here is my code:
Frame/Panel class
package movingball;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public  class  MovingBall  extends  JFrame
    protected  final  int  FRAME_WIDTH  = 240;
    protected  final  int  FRAME_HEIGHT  = 320;
    private BallPanel myPanel;
    public  MovingBall  (String  title)
        super(title);  
        setSize(FRAME_WIDTH,  FRAME_HEIGHT);
        setLocation(400,400);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myPanel = new BallPanel();        
        add(myPanel);
    private class BallPanel extends JPanel
        private Ball ball;
        public BallPanel()
            ball = new Ball(FRAME_WIDTH, FRAME_HEIGHT);
            addKeyListener(new BallWatcher());
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            ball.paint(g);
        private class BallWatcher extends KeyAdapter
            public void keyPressed(KeyEvent k)
                if (k.getKeyCode()==KeyEvent.VK_LEFT)
                    ball.moveLeft();
                if (k.getKeyCode()==KeyEvent.VK_RIGHT)
                    ball.moveRight();
                repaint();
            } // end keypressed
        } // end ballwatcher
    } // end ball panel
} // end moving ballBall class:
package movingball;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
public class Ball
    private  final  int  RADIUS  = 10;
    private  int move;
    private  Point  pos;
    private  Color  ballColour;
    private  int  height,  width;
    public  Ball  (int  frameWidth,  int  frameHeight)
        move = 3;
        ballColour = Color.RED;
        width  = frameWidth;
        height  = frameHeight;
        pos  =  new  Point();
        pos.x  = 0 + RADIUS;
        pos.y  = 0 + RADIUS;
    public void moveLeft()
        if(pos.x - RADIUS > 0)
            pos.x = pos.x + move;
    public void moveRight()
        if(pos.x + RADIUS < width)
            pos.x = pos.x + move;
    public void paint(Graphics  g)
        g.setColor(ballColour);
        g.fillOval(pos.x,  pos.y,  2*RADIUS, 2*RADIUS);
}Many thanks in advance,

JPanel are not focusable by default and key events are sent to the focused component. Use JPanel#setFocusable(true) to make it focusable or use keybinding on the JFrame (search on "java keybinding tutorial").

Similar Messages

  • Need Help Making Flash Intro Movie

    I have a 30 second .wmv movie I need to convert to a flash
    format. No problem.(fla or swf)? But, I would like it to play
    before going into my main website with a skip into button. I need a
    preloader and to have it go directly onto the index.html (first
    page of the website) after playing. I have mad many failed
    attempts! Can anyone help me do this?
    Thank You,
    [email protected]

    actually - let me re-phrase that; who would sit and wait to
    download a 30 minute intro before
    entering a site?
    There's plenty of info in the help docs about flash video -
    tons of articles on adobe's site
    dedicated to flash video - google is your friend here.
    ~~~~~~~~~~~~~~~~
    --> Adobe Certified Expert
    --> www.mudbubble.com
    --> www.keyframer.com
    ~~~~~~~~~~~~~~~~
    Chris Georgenes wrote:
    > 30 minute intro? That's about the biggest oxy-moron I
    have ever heard
    > of. I think you are trying to do something nobody else
    would ever do -
    > who would sit and watch something for 30 minutes before
    entering a site?
    >
    > ~~~~~~~~~~~~~~~~
    > --> Adobe Certified Expert
    > --> www.mudbubble.com
    > --> www.keyframer.com
    > ~~~~~~~~~~~~~~~~
    >
    >
    >
    >
    > MXBrian wrote:
    >
    >> I have a 30 minute .wmv movie I need to convert to a
    flash format. No
    >> problem.(fla or swf)? But, I would like it to play
    before going into
    >> my main website with a skip into button. I need a
    preloader and to
    >> have it go directly onto the index.html (first page
    of the website)
    >> after playing. I have mad many failed attempts! Can
    anyone help me
    >> do this?
    >>
    >> Thank You,
    >> [email protected]
    >>

  • 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.

  • Making a shape move in Flash 8..Help

    I am trying to make a ball move, it's all perfect apart from this:
    Statement must appear within on/onClipEvent handler = ( isJumping) = false;)
    Then I put in "on", then it says:
    Unexpected 'on' encountered.
    That's a bit of fail, any help?
    I will post the full code if needed.

    if you have any valid code attached to a frame you can leave it but, my guess is you don't have any valid code.  but if you don't want to remove code that might be serviceable, you can surround the code with a comment demarkation:
    your code

  • Help making a Install USB of os x 10.4.6. for my Macbook 1.8ghz

    Hi,
    I need help making the USB install of os Tiger.
    The drive is having trouble reading the install disc I own so I am trying to make a USB install of it.
    I wantto install from the usb not install to it to be clear.
    Things I have!
    X1 8gig sandisk flash drive
    1 Macbook white 1.8 ghz Intel
    1 Pc with Macdrive 7
    1 Install disc that seems to have trouble being read in the drive > few marks on the disc and the mac DVD drive make lots of noise reading it but
    It will go to Disk utilities.
    Seems to be a bug in Tiger and restore doesn’t seem to work as in I can’t drag and drop a source to the restore the DVD to the flash drive.
    I already tried only 1 time to copy the DVD to the formatted flash drive using Macdrive and it read it as a bootable drive but the apple simple came up
    And then I got a the error (Can’t find driver for this platform error APCH or something like that.
    I have a torrent download of OS x 10.4.6 as well just in case some files are corrupted > I own the disk so it’s not illegal.
    I am new to mac but long time user of PC.

    Ok ..you need another Mac to make this work!
    you just use another mac even a old one like g4 to make a restore to a flash drive that you have formatted and verified.
    Bye
    Sam

  • Need HELP - Duplicating a DVD (movie)

    Is anyone able to help me copy a movie onto my macbook so I can place it on my ipod? Please!?!?!?
    Message was edited by: DWSLAS

    Hi DWSLAS,
    You may not be allowed to duplicate the movie, but you are entitled to make a backup of it. I use a neat little program called Handbrake follow this link to download it and it will do exactly what you want! Good Luck!
    http://handbrake.fr/?article=download
    Regards
    Stu

  • Help with QT Reference Movie

    Because I moved from using Sony Vegas to FCP, I didn't keep the SD card structure intact. I only kept the .mts files. Because of this, I used ClipWrap to convert to Apple ProRes 422 LT. I imported this footage into FCP and put it on the timeline and used PluralEyes to sync. I wanted to create a QT Reference Movie of V1, but for some reason, FCP wants to render out the entire track completely (over 46 gb) instead of just making a reference movie. Why is this? Here's a screen shot of what I'm doing:
    https://skitch.com/everydayjones/gugxb/skitch

    >I used ClipWrap to convert to Apple ProRes 422 LT
    But does that match your Sequence settings in FCP?  Frame rate?  Pixel dimensions?  If any settings don't match, or when you've applied effects to the clips in the Timeline, FCP will render the Sequence and those renders will become part of the Reference movie.
    Render the Sequence fully before you export and the resulting reference file will be much smaller in size.
    -DH

  • HT200109 Help! Cant buy movies on itunes through apple tv as it keeps telling me my credit card has expired.It has been updated through my pc.

    Help! Cant buy movies on itunes through apple tv.Keeps telling me my credit card has expired despite having updated info on my pc.?

    *know :/

  • 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.  :-)

  • Help making a logon page

    I need help making a simple logon page in Dreamweaver MX. I
    have tried Visual Basic. and several other methods to no avail. If
    someone could help me it would be greatly appreciated
    Ron Hansen

    Hi Ron
    The proceedure is pretty much the same in
    PHP/Coldfusion/JSP/ASP.
    There is a very easy to follow example in the Dreamweaver
    Help File.
    Just go to Help-->Developing Applications Rapidly -->
    Building pages that restrict access to your site (ColdFusion, ASP,
    JSP, PHP) --> Building a login page
    I don't think it can get much easier. But remember that you
    will need to have a database table of user details in place to
    complete the process.
    Good luck.

  • Need Help making a Screencast for IPHONE

    Hello there
    I need some serious help making a screencast for a client - for it's Iphone Apps -
    something similare to this
    http://www.newsluxe.com/chaumet-et-iphone.php
    but more sexy, with a animated background and a different type of cursor.
    Anyideas ?
    I really don't know where to start - I found leads however :
    Camtasia Studio , screenflow, ,
    Maybe you could help me filling the gaps.
    Thanks for your help !

    does anyone know how apple made these forums?
    I think they use Jive:
    http://www.jivesoftware.com/products/forums/
    The Apple way for users to add photos is the .Mac web gallery:
    http://www.apple.com/ilife/iphoto/#webgallery

  • Can anyone help me find my movies from my old PC?

    Can anyone help me find my movies on my MacBook Pro from my old PC? I am on Mac OS X, Lion version 10.7.5, use iPhoto, and have a  2.4 GHz Intel Core i5 processor from late 2011. I had the geniuses transfer my old hard drive to the MacBook Pro a couple of years ago and now I don't know where they ended up. They are not in iMovies since today was the first day I ever opened that App!
    I have searched through Finder but I only find a few of them. I am certain they are there somewhere, however. I read another discussion and it said to go to you HOME folder in finder. But I don't see a way to do that. So I have been searching by MOV in "All my files." Unfortunately just a few of them are showing up. Any  new suggestions?

    Thanks for helping out.
    Yes, I should have mentioned that before. I have been searching This Mac too. In fact, I have been trying all kinds of queries to find them, hoping that I'll happen upon the kind of file they are. I tried .mp4 and found a lot of music stuff but not the family movies I am looking for.
    Maybe you are right. Maybe they were some weird Windows only kind of file and they didn't transfer to Mac. The good news is that I have them all on the PC, which is still working. I just need to figure out a place to keep them that's secure so we don't lose them...

  • 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.

  • HT3775 For some reason my QuickTime player has stopped playing all my .avi movies, I can't seem to upgrade and it doesn't offer any solutions except that it may need additional software but not what or where to obtain it from? Help most of my movie are in

    For some reason my QuickTime player has stopped playing all my .avi movies, I can't seem to upgrade and it doesn't offer any solutions except that it may need additional software but not what or where to obtain it from? Help most of my movie are in .avi!!

    Google 'Perian' and 'Flip4Mac' — these are the extensions that will make QT play other file formats.
    However, a simpler solution is just to abandon QT in favour of the free, open-source player VLC, which plays just about everything natively without further downloads.
    Download the free VLC Player from here:
    http://www.videolan.org
    Plays just about everything, including avi & mpg, without add ons.

  • I need help to transfer my movies from I tunes to an external hard drive please

    I need help to transfer my movies from I tunes to an external hard drive please

    Teach a man to fish, feed them for life.
    https://discussions.apple.com/message/16276201#16276201

Maybe you are looking for

  • How to get values from a stored package variable of type record ?

    Sir, In my JClient form, I need to get values from a database stored package variable of type record. And the values are retained in the JClient form for the whole session. The values are copied only once when the form is started. What is the best wa

  • How do I create a location indicator in Adobe Muse?

    For example, the location indicator for this page is in the upper left and reads as follows: Adobe Community > Help with using Adobe Muse CC I would like to provide the same feature on my Muse website. Thank you. Bernie

  • Calendar questions/trouble...

    I will admit I do not know much about my iPhone accept to IM, make phone calls, and listen to tunes; just the basics in communication.  I am wanting to use the calendar functions, however, I do not care for the default calendar that comes with the ph

  • Images collapse when viewed in IE on a PC

    I have designed my site with DW CS3 on a Mac. When I view the site using Firefox or Safari, all the images look fine, but when the site if viewed on a PC with IE the images collapse (shrink). Sometimes the problem is fixed by refreshing the site but

  • Single port forwarding

    wrvs4400n on the new port forwarding it has 1 blank spot at the bottem the others filled in but not enabled. I have used the blank with port 80 on a IP cam and now have another IP cam and need to use another, do I just change one of the other ones fi