How to simply mimic a moving ball in an applet

Hi,
I'm new to Java and trying to understand some basics. I have a small problem; all i want to do is to draw a circle within an applet window, make it move slightly and then repaint it (setting a start and end parameter).
Now, i can get the circle to appear in the window, but it won't redraw it to the next part of the screen. The code, hopefully, will make things clearer. Any help appreciated.
//import the relevant libraries
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
public class J11Applet extends Applet
     public void init()
          setBackground(Color.yellow);               
     class Ball                                        //class ball
          int x;
          int y;
          int dx=1;
          Ball(int setX, int setY)
               x=setX;
               y=setY;               
          public void paint(Graphics g)          //draws an oval, i.e. the ball.
               g.setColor(Color.blue);
               g.drawOval(x,y,50,50);
          void move()                                   //makes the ball move direction
               if (x>=800-120)
                    dx=-dx;
               if (x<=0)
                    dx=-dx;
               x=x+dx;
     public void start()
     public void paint(Graphics g)               //paints on the applet window
          Ball myBall = new Ball(5,5);
          myBall.paint(g);
          myBall.move();
          repaint();
     public void stop()
     public void destroy()
}

If you want something doing something by itself, it needs to have a thread driving it, either implicitly (by creating a Thread) or implicitly (by using something like Timer/TimerTask, which creates its own thread).
Or I suppose you could do something hideous, like hijack the GUI update thread to update object state, but that's unreliable and can mess up GUI responsiveness.
So in an application you need threads as well (even if you do it implicitly or hideously as described above). I don't know what you were doing before to make a ball move in an application, but if it were doing it by itself (not just clicking a button over and over) then it involved a thread somehow.

Similar Messages

  • Why does it come out as a line instead of a moving ball?

    I wish to have a moving ball, but got a growing line, anybody can let me know how to solve it?
    Thanks
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.lang.*;
    public class Bouncer extends javax.swing.JApplet implements Runnable {
        /** Creates a new instance of Bouncer */
        public Bouncer() {
        int rectW, rectH, rectPosX, rectPosY;
        int ballW, ballH, ballPosX, ballPosY, dx, dy;
        Thread ballThread;
        public void init()
            rectW = 5000;
            rectH =5000;
            rectPosX = 0;
            rectPosY = 0;
            ballW =10;
            ballH = 10;
            ballPosX =20;
            ballPosY = 20;
            ballThread= new Thread(this);
            ballThread.start();
        public void paint(Graphics g)
         g.drawRect(rectPosX, rectPosY, rectW, rectH);
         g.drawOval(ballPosX, ballPosY, ballW, ballH);
         g.setColor(Color.black);
         g.fillOval(ballPosX, ballPosY, ballW, ballH);
         g.dispose();
        public void move()
           dx =2;
           dy=2;
          ballPosX += dx;
          ballPosY += dy;
          repaint();
        public void run() {
            while((ballPosX < rectPosX + rectW) && (ballPosY < rectPosY + rectH))
                try
                    ballThread.sleep(100);
                catch(InterruptedException e)
                {e.getMessage();}
                move();
    }

    OK, were you trying to use drawRect() to erase the ball? That won't work since the new ball might not be in the same rectangle as the old one. Try this:public void paint(Graphics g)
        // Erase old ball
        // Note: bkgdColor should have already been set
        // to your background color (probably white)
        g.setColor(bkgdColor);
        g.fillOval(ballOldPosX, ballOldPosY, ballW, ballH);
        // Draw new ball
        // Note: fgndColor should have already been set
        // to your foreground color (probably black)
        g.setColor(fgndColor);
        g.fillOval(ballPosX, ballPosY, ballW, ballH);
        g.dispose();
    }

  • Once an iBook has been exported to the iPad, how can that book be moved to a different iPad or back to iBooks Author?

    Once an iBook has been exported to the iPad, how can that book be moved to a different iPad or back to iBooks Author?

    You can't simply move it directly between iPads.
    In your example, you'd find that .ibook file in your iTunes account on your computer and then email or sync it to the school's iPad. Similar to how you did with yours....maybe you got it off a server and can repeat that process.
    Then delete it off your iPad and either delete or flag your copy in iTunes to not be put back when you sync in the future.

  • How to SIMPLY use the %DIMENSION_TO_SET% variables into logic scripts

    hello,
    I'm using a prompt of type "COPYMOVE" or "COPYMOVEINPUT". In this type of prompt, there are 2 columns of dimension members list, one for defining the "source zone" and one for defining the "target zone" of logics.
    The left colum of the prompt (for source zone) feeds the variables %DIMENSION_SET% : %ACCOUNT_SET%, %ENTITY_SET%, %CATEGORY_SET%, etc...and these variables can be used in the logic scripts in *XDIM_MEMBERSET instructions for example.
    The right colum of the prompt feeds the variables %DIMENSION_TO_SET% : %ACCOUNT_TO_SET%, %ENTITY_TO_SET%, %CATEGORY_TO_SET%, etc...and I don't know how to SIMPLY use these variables in the logic scripts.
    I've found a tricky way to do that but I meet 2 problems :
    - it is complicated
    - the multi-info instruction (BEGININFO/ENDINFO) seems to be bugged as blank lines are added all the time in the code and sometimes I have to wait for minutes when I try to modifiy the package code through BPC for excel eData/modify package menu.
    So the question is how to SIMPLY get the %DIMENSION_TO_SET% variables into logic scripts and use them ? Thanks, R.
    Here is the tricky package code I use at this time (I build one function for each %DIMENSION_TO_SET% variable and I pass these functions to the logic) :
    PROMPT(COPYMOVE,,,,"ACCDETAIL,ACCOUNT,CATEGORY,DATASRC,ENTITY,TIME,YEARS")
    TASK(Execute formulas,USER,WS-WW\PlauchuR)
    TASK(Execute formulas,APPSET,US)
    TASK(Execute formulas,APP,SV)
    TASK(Execute formulas,SELECTION,D:\BPC\Data\WebFolders\US\SV\PrivatePublications\PlauchuR\TempFiles\FROM_1561_.TMP)
    TASK(Execute formulas,TOSELECTION,D:\BPC\Data\WebFolders\US\SV\PrivatePublications\PlauchuR\TempFiles\TO_1561_.TMP)
    BEGININFO(%FSS%)
    *FUNCTION TARGETACCDETAIL=%ACCDETAIL_TO_SET%
    *FUNCTION TARGETACCOUNT=%ACCOUNT_TO_SET%
    *FUNCTION TARGETCATEGORY=%CATEGORY_TO_SET%
    *FUNCTION TARGETDATASRC=%DATASRC_TO_SET%
    *FUNCTION TARGETENTITY=%ENTITY_TO_SET%
    *FUNCTION TARGETTIME=%TIME_TO_SET%
    *FUNCTION TARGETYEARS=%YEARS_TO_SET%
    ENDINFO
    TASK(Execute formulas,FORMULASCRIPT,%FSS%)
    TASK(Execute formulas,LOGICFILE,D:\BPC\Data\WebFolders\US\SV
    ..\AdminApp\SV\_TEST.Lgf)
    TASK(Execute formulas,RUNMODE,1)
    TASK(Execute formulas,LOGICMODE,1)
    Edited by: ALEXANDRE BEDIER on Jun 16, 2010 3:15 PM

    hello,
    finally I've discovered that there is no need of BEGININFO instruction.
    One can pass several functions to a logic with one FORMULASCRIPT task. The functions definitions have to be separated by instructions. See below :
    PROMPT(COPYMOVEINPUT,%FTARGETS%,,"select source and target zone for category and datasource.","ACCDETAIL,ACCOUNT,CATEGORY,DATASRC,ENTITY,TIME,YEARS")
    TASK(Execute formulas,FORMULASCRIPT,*FUNCTION TACCDETAIL=%ACCDETAIL_TO_SET% *FUNCTION TACCOUNT=%ACCOUNT_TO_SET% *FUNCTION TCATEGORY=%CATEGORY_TO_SET% *FUNCTION TDATASRC=%DATASRC_TO_SET% *FUNCTION TENTITY=%ENTITY_TO_SET% *FUNCTION TTIME=%TIME_TO_SET% *FUNCTION TYEARS=%YEARS_TO_SET%)
    TASK(Execute formulas,USER,%USER%)
    TASK(Execute formulas,APPSET,%APPSET%)
    TASK(Execute formulas,APP,%APP%)
    TASK(Execute formulas,SELECTION,%SELECTIONFILE%)
    TASK(Execute formulas,LOGICFILE,%APPPATH%\..\AdminApp\%APP%\_TEST.LGF)
    TASK(Execute formulas,RUNMODE,1)
    TASK(Execute formulas,LOGICMODE,1)
    Then one will be able to use the functions TACCDETAIL, TCATEGORY, TACCOUNT,... in the logic script.
    Edited by: ALEXANDRE BEDIER on Jun 24, 2010 10:31 AM
    Edited by: ALEXANDRE BEDIER on Jun 24, 2010 10:33 AM

  • Does anyone know how to simply edit the text in the spine of hard cover, 40 page book in the book mo

    Does anyone know how to simply edit the text in the spine of hard cover, 40 page book in the book module? I can click into any other text window and edit and change attributes but I am locked out of editing text when it comes to the spine of the book. I spoke to Blurb support and they referred me to Adobe. I spent 45 minutes with support here - no one knew. I am still waiting for a call back with an answer... not holding my breath as it's been a few hours now. HELP!!!

    Thanks for your reply John. I have experienced all the fiddly aspects you mentioned - these are attributes and although changing them requires the skill of a surgeon's hand - it's the actual editing of the text I can't seem to access anymore. The box just won't allow me to do anything except change attributes. Does that make sense? And it's only on the spine where I am having this issue. Puzzled! I have even rebooted the program and just now the computer - to no avail. 

  • I tried to encrypt using file vault but it froze slowing my macbook pro, how can i get things moving or stop the encryption

    i tried to encrypt using file vault but it froze slowing my macbook pro, how can i get things moving or stop the encryption

    Back up all data before proceeding. There are ways to back up a computer that isn't fully functional. Ask if you need guidance.
    Start up in Recovery mode. When the OS X Utilities screen appears, select Disk Utility.
    In the Disk Utility window, select the icon of the startup volume from the list on the left. It will be nested below another disk icon, usually with the same name. Click the Unlock button in the toolbar. When prompted, enter the login password of a user authorized to unlock the volume, or the alternate decryption key that was generated when you activated FileVault.
    Then, from the menu bar, select
              File ▹ Turn Off Encryption
    Enter the password again.
    You can then restart as usual, if the system is working. Decryption will be completed in the background. It may take several hours, and during that time performance will be reduced.
    If you can't turn off encryption in Disk Utility because the menu item is grayed out, you'll have to erase the volume and then restore the data from a backup. Select the Erase tab, and then select
              Mac OS Extended (Journaled)
    from the Format menu.
    You can then quit to be returned to the main Recovery screen. Follow these instructions if you back up with Time Machine. If you use other backup software, follow its developer's instructions.
    Don't erase the volume unless you have at least two complete, independent backups. One is not enough to be safe.

  • How to get rid of moving lighted square on iPhone 5s

    how to get rid of moving lighted square on iPhone 5s

    Triple click the home button to get out of it.  Then:
    Settings > General > Accessibility > Switch Control > OFF

  • How to get Material Master Moving average price into Purchase Order

    Hi,
    How to get Material master moving average price into purchase order instead of Purchase Info record.
    Thanks,
    Sridhar

    Hi,
            I  cannot understand whether it is necessary .
           How about as following step?
                 1. create Purcahse requisition
                                Price come form moving average price in material master.
                 2. Create Purchase order reference Purchase  requisition
                                There is a setting  from the unit price of P/R onto the unit price of P/O.
      Regards,
         Gaito

  • How do I stop the spinning ball?

    How do I stop the spinning ball? It has just begun in the last couple of days. Very annoying. Must wait 10-20 seconds to access an Internet site or information into a Google site. It even stopped me in the midst of typing this message.
    JunieB

    Troubleshoot the spinning beach ball

  • Sculpture morph pad-How do I get the red ball?

    I just worked my way thru the Sculpture tutorial, creating a pad. Everything works except that I'm not getting the red ball in the morph pad. I do see it on other presets, but not with the sound I made from the default patch. How do I get the red ball?

    Nice work. To activate the red ball, you need to activate the Morph Envelope Parameters. It's the area underneath the morph pad. Across the top there are options: "Mode", "Time Scale", "Sustain Mode". Click and hold under Mode where it says "Off". You'll get a menu of options, select "Pad only" and the red ball appears. Or you can edit the actual morph envelope to the other options.
    For a more detailed explanation see page 406 in of the plug-in reference guide.

  • Need Photoshop action to record WHERE on canvas a layer is placed, NOT how many pixels it was moved.

    Hello everyone,
    I'm pulling my hair out trying to figure this out.
    I created an action:
    I have a bunch of PSD files of some pretty expensive rings that were shot at hi-res and cropped.
    Now, i have a canvas that is 996x1104 px.
    All of these rings must sized to 540px width AND positioned on the canvas at x:498px and y:706 (the bottom of the layer must touch 706px, which I did by clicking on the little tiny box at the bottom of the little square made of little squares (that's next to the x and y positions when you are on Transform mode).
    I made an action for all of these steps.
    However, when I batch a group of these hi-res ring PSDs and apply the action,
    they are always in different spots. They all need to be set on y:706px so it looks like they are all resting on the same plane.
    I found out why this is happening:
    because when I position the ring when creating the action, Photoshop records HOW MUCH in pixels I moved the layer... NOT WHERE ON THE CANVAS IT'S POSITIONED.
    This is what I need: to have Photoshop record WHERE on the canvas the layer is positioned.
    Can anyone help?
    We have so much work to do by Monday and setting up this action would definitely help us.
    Thanks so much!
    _Chris

    Did you try settings the rulers units to Percent before recording the action and see if that makes a difference?
    You might possibly need a script for your goal, in which case you could ask over on the photoshop scripting forum:
    http://forums.adobe.com/community/photoshop/photoshop_scripting

  • How do I stop the spinning ball that keeps going and going and going

    How do I stop the spinning ball that keeps going and going and going.  I think I have to remove cookies, but I don't know how.

    I think I solved it.
    I searched my extensions folder (in my profile) for all image files (PNG and JPG), and found the pop-up images to be in an extension folder related to Firefox Sync (not an external extension, actually). But even though I had already disabled it and un-linked this computer from Firefox Sync, the message still popped-up.
    I think the image filename was SYNC.PNG, or something like that. Close Firefox, find the folder where that image is in, and rename the main folder (the one right under the extensions folder) to some other name (such as "original name_copy"). Then start Firefox. Check if it works OK and if the pop-up ceases to appear. If everything OK, then you can delete that folder.
    If something goes wrong, just rename the folder to what it was before.

  • How to simply make the new ipod touch appear on itunes when it have been working in the previous computer (mac)

    how to simply make the new ipod touch appear on itunes when it have been working in the previous computer (mac)

    If the new computer is a PC see:
    iPhone, iPad, or iPod touch: Device not recognized in iTunes for Windows
    If a Mac:
    iPhone, iPad, iPod touch: Device not recognized in iTunes for Mac OS X
    Mac OS X v10.6 or later: iOS device not recognized in iTunes after restart

  • How to Call Livelink Archive Java Viewer(IXOS-JavaViewer Applet )

    Hi,
    I want you to teach,How to call Livelink Archive Java Viewer(IXOS-JavaViewer Applet)
    I want to call it in the following images.
    When the button is pushed, I want to call Livelink Archive Java Viewer.
    The method was not able to be taught though it inquired of the help desk of
    IXOS.
    Please teach me!
    Reagard

    Hi Tomohiro,
    Is this issue being resolved? which version of ixos server and viewer are you using?
    regards,
    Jess

  • How do I write an installation program for my applet?

    I have created an applet that uses swing and connects to a database. I'd like to write an installation program so that it's possible to install the applet on any system.
    How can I do? a batch-file?

    Applets run within web browsers. All you need to "install" it is a machine with a web browser and the Sun java plug-in for that browser.
    If you mean you've written an "application", you have several options.
    1) you can distribute it as an executable jar file
    2) you can distribute it with a launcher bat file / executable
    3) you can distribute it using something like InstallShield for Java
    4) you can distribute it using some other third party java installer.
    McF

Maybe you are looking for

  • Alpha Numeric - GL account numbering

    Hi Our client is going for alpha numeric GL accounts. FS00 will allow creating alpha numeric GL accounts. But i wanted to what may be problem in future? I want to know will any account determination settings like OBYC (FI - MM Settings), VKOA (FI - S

  • Internal Pioneer DVD drive to an external drive

    Hi there I recently bought a S-ATA & IDE USB 2.0 Adaptor to rectify my Firewire connection going down , recently. I can now connect my old external Firewire hard drives via USB 2.0. Great!! However I realised that this adaptor also allows me to power

  • LSMW Multiple Files

    Hi All, I have the records in the following pattern.   Key Record   REC_KEY1        CLASS1    CHAR1 CHAR_VALUE1                             CHAR2 CHAR_VALUE2                   CLASS2    CHAR3 CHAR_VALUE1                             CHAR4 CHAR_VALUE4

  • Is there an outage in suburban Chicago? TV down all night and morning

    Is there an outage in suburban Chicago? My tv out all night and morning? When can I expect to be back up ty

  • How do I set up a rescue email!?

    Please help I don't know how to do it