Running a "worm" around edge of JComponent.

Hello all.
I am currently working on a little class that will draw a "worm" onto any JComponent and run it around the edge (clockwise, starting in upper left corner) of that JComponent. Currently the worm is just a simple Rectangle2D (a 10x10 square), but I want to extend it into an elongated rectangle with a gradiant tail. Baby steps though. :)
My worm is currently working, with 2 issues that I am hoping some folks could help me with. The current code is at the end of the message.
(1) My worm sometimes jumps beyond the boundries of the JComponent it belongs to. I have some math set up to avoid this, but I seem to be missing something obvious because it is still happening!
(2) There is a slightly flicker associated with the movement of the worm. I'm not sure if double buffering will really help in this case because the redraw is very simple. Perhaps I just haven't found the right mix of "speed" and "delay". If anyone has thoughts on this I woudl appreciate the input.
(3) Okay... 3 things. I'm just looking for tips on cleaning up the code. My hopes are to extend this to having a gradient tail and to actually crawl around corners too. General input on how I might change things now to make things easier in the future would be greatly appreciated!
Thanks much for any input! Code follows:
public class Worm implements Runnable {
     private JComponent world;
     private boolean isRunning = false;
     private Thread wormThread;
     private Rectangle2D worm;
     private int speed = 10;
     private int delay = 100;
     private int xVelocity = speed;
     private int yVelocity = 0;
     public Worm(JComponent widget) {
          this.world = widget;
          worm = new Rectangle2D.Double(0, 0, 10, 10);
          wormThread = new Thread(this);
     public void run() {
          while (isRunning) {
               /** calculate the worm's new location */
               double newX = worm.getX() + xVelocity;
               double newY = worm.getY() + yVelocity;
               /** make sure the worm does not run out of bounds */
               if (newX + worm.getWidth() > world.getWidth())
                    newX = world.getWidth() - worm.getWidth();
               if (newY + worm.getHeight() > world.getHeight())
                    newY = world.getHeight() - worm.getHeight();
               newX = (newX < 0) ? 0 : newX;
               newY = (newY < 0) ? 0 : newY;
               /** redraw the background, with a little buffer for safety */
               Rectangle prevBounds = new Rectangle((int)worm.getX()-1, (int)worm.getY()-1, (int)worm.getWidth()+2, (int)worm.getHeight()+2);
               world.repaint(prevBounds.getBounds());
               /** update the worm's location */
               worm.setRect(newX, newY, worm.getWidth(), worm.getHeight());
               repaint();
               /** change the worm's direction as needed */
               if (xVelocity > 0 && newX + worm.getWidth() >= world.getWidth()) {
                    xVelocity = 0;
                    yVelocity = speed;
               } else if (yVelocity > 0 && newY + worm.getHeight() >= world.getHeight()) {
                    xVelocity = -speed;
                    yVelocity = 0;
               } else if (xVelocity < 0 && newX <= 0) {
                    xVelocity = 0;
                    yVelocity = -speed;
               } else if (yVelocity < 0 && newY <= 0) {
                    stop();
               /** take a short nap */
               try {
                    Thread.sleep(delay);
               } catch (InterruptedException e) {
                    e.printStackTrace();
     private void repaint() {
          Graphics2D g2d = (Graphics2D)world.getGraphics();
          g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2d.setPaint(Color.ORANGE);
          g2d.fill(worm);
          g2d.draw(worm);          
          g2d.dispose();
     public void start() {
          isRunning = true;
          wormThread.start();
     public void stop() {
          /** stop the worm */
          isRunning = false;
          /** redraw the world to clear up any remnants */
          world.repaint();
}

The worm flicker could be solved by double buffering, but it could also be down to the the actual frames per second which are being achived. 85 FPS would be ideal. The trouble is the call to repaint() and the call to Thread.sleep() both return when the JVM feels like it and this could vary depending on the load placed on your machine at the time.
So measuring how many loops are occuring in a second might be start.
To clean up the code it might be worh factoring the loop into:
public void run() {
          while (isRunning) {
                    updateGameState();
                    repaint();
                 }The worm would update its own state with worm.move() which would be called in updateGameState(); Therefore moving the move logic from run() to the worm, ofcourse the worm would have to have a reference to its world!

Similar Messages

  • RE: 2211x monitor. Removed clear film around edge but does the long sticker at the top come off?

    RE: 2211x monitor.  I have removed the clear film around edge of the black monitor but does the long sticker advertising features at the top come off? I don't want to try and realizes it is well and truly glued on.
    This question was solved.
    View Solution.

    It should come off, and if you are scared you can use goof off if it leaves pieces behind, or just rub your thumb or finger over it until it becomes hot then pieces should come off.
    Please give Kudos. What other kind of recognition could I get?
    Have I solved your problem? Mark solution as accepted.
    I try to hate Macintosh. I really do. But I can't bring myself to hate any electronic device.

  • Pixel around edge on Chroma key

    I have trouble to remove green edge around me. I add spill suprresor green. but it show gray on edge. i have to use soften edge that cause gray on edge.
    I don't understand why bad pixels around edge. That cause me struggle to remove gray edge.
    Why pixels?
    I use DV on HDV camera but DV setting.
    I use chroma keyer, color smoothing-4.1.1, spill supressor-green, FCP 7
    I thought I have plenty light but apparently not. 5 lights. 2 dome on green, 2 key lights on me, one back light.
    Thanks

    yep  your far too close
    you must have a good separation between the subject and the background
    as a rough guide in setting up;    the subjects shadow  coming from the main light should not be able to fall on the background, if it is, move the subject further away.
    The chroma keyer in FCP is very basic and needs a very good lighting set up to make it function
    good level of illumination, even flat lighting on the back ground,  good 3 point lighting on the subject to separate from the background.

  • Drop Shadow Around Edge of Website

    I am trying to make a drop shadow all around the edge of a site in Dreamweaver CS4. I know I need to make a container around the wrapper and place it as a background image and repeat y. I know how to make the graphic in PS. What I can't figure out is how to make it look like it flows into the body background color. If the body has a sold background color it's not a problem, but what if the body backround is a gradient? If there is a gradient it doesn't look correct because I can't pic a color for my layer under the shadow in photoshop.
    Also how do I get the background to show at the very bottom of the page.
    Please help I have been trying to figure this out for hours

    Also how do I get the background to show at the very bottom of the page.
    If you are talking about a gradient, there are two ways to give that appearance.
    1. Make the gradeint image longer that the page, for example create the gradient a size like 5px x 2500px.  You will run into issues on differnet height pages.
    or
    2. And I thin a better suggestion.  Create your gradient, then have it blend into the the background color.  So for example if your gradient goes from black to light gray, make the background color the last light gray of your image...then it blends.  On extra long pages you lose the gradient.
    Gary

  • How can I print with black border around edge of image?

    I'd like to add a black border around the edge of certain images I'm printing. I know it's fairly trivial in Lightroom, but I can't see where this option is in Aperture. Is this lacking in Aperture, or am I just missing it? Many thanks.
    PS -- I'm aware there are some plug-ins that claim to do this, so if Aperture can't do this, please feel free to chime in with comments on the best plug-in for this task.

    Rich Hayhurst wrote:
    Here's what you need:
    http://www.apple.com/downloads/macosx/aperture/apertureborderfx.html
    Aperture BorderFX 1.1
    Thanks, Rich. That's a good plug-in, and does cover what I need (with lots of other features, too). The problem, though, is it requires an export of the image, which I then have to either print from another application, or reimport to Aperture to print. I was hoping to find something that will either just apply the border to the print job, or that would serve as more of an Edit With . . . type of plug-in than an Export plug-in, so I can keep everything in one place. Thanks again.
    Message was edited by: jeffd55

  • Can't get rid of gap around edge

    Hi there,
    I'm struggling to get rid of the gap around the edge of the website I've just started building.  I've got the margins set to 0 for the top, and the divs are 100% width.  Does anybody have any ideas?  I've attached a picture to demonstrate and also please see the code pasted in below, in case that's useful.
    Thanks,
    Mark
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style type="text/css">
    <!--
    #header {
        background-image: url(images/header_background.jpg);
        background-repeat: repeat-x;
        height: 230px;
        width: 100%;
        margin-top: 0px;
    #navbar {
        background-image: url(images/navbar_background.jpg);
        background-repeat: repeat-x;
        height: 34px;
    #container_navbar {
        height: 34px;
        width: 852px;
        margin-right: auto;
        margin-left: auto;
    #main_text {
        background-image: url(images/maintext_background.jpg);
        background-repeat: repeat-x;
        height: 536px;
        width: 100%;
    #container_header {
        background-image: url(images/header_image.jpg);
        background-repeat: no-repeat;
        margin-top: 0px;
        margin-right: auto;
        margin-bottom: 0px;
        margin-left: auto;
        height: 230px;
        width: 852px;
    #container_maintext {
        height: 536px;
        width: 852px;
        margin-right: auto;
        margin-left: auto;
    #footer {
        background-image: url(images/footer_background.jpg);
        background-repeat: repeat-x;
        height: 200px;
        width: 100%;
    #container_footer {
        height: 200px;
        width: 852px;
        margin-right: auto;
        margin-left: auto;
    -->
    </style>
    </head>
    <body>
    <!--Header-->
    <div id="header">
      <div id="container_header"></div> 
    </div>
    <!--Navbar-->
    <div id="navbar">
      <div id="container_navbar">SPRY MENU GOES HERE</div>
    </div>
    <!--Main Text-->
    <div id="main_text">
      <div id="container_maintext">MAIN CONTENT GOES HERE</div></div>
    </div>
    <!--Footer-->
    <div id="footer">
      <div id="container_footer">FOOTER CONTENT GOES HERE</div>
    </div>
    </body>
    </html>

    Add the below to your css styles:
    body {
    margin: 0;
    padding: 0;

  • White border around edge of pdf (not picture related)

    I've been fumbling with this for days and can't figure it out.  I guess that means it's probably something really simple.
    I'm using CS5 and am trying to create a book cover for self-publishing.
    The artboard is set to 17.28" wide and 11" tall with .125 bleed.
    I created a blue rectangle (no stroke) as a background to cover the artboard and the bleed so it measures at 17.53" wide (17.28"+.25") and 11.25" tall.
    Theoritically that should work?  However, when I save as a pdf (or print to pdf), the document size is 17.53" wide and 11.25" tall, but there is a white gap around the top/bottom/right edge.
    I've tried:
    - making the rectangle larger than the bleed section
    - making the artboard a little larger
    - no stroke/with stroke around the rectangle (thinking it had something to do with what others have been experiencing with white lines)
    - making sure smooth line art is selected
    - a host of other things
    .. but no change.
    Image is attached, but may need to zoom in to see problem.
    Any help is greatly appreciated.
    Thanks.

    Hi Jacob,
    Thanks for the response.
    I tried your suggestions - no change.
    It's a simple file with not a lot of complicated items, basically just three rectangles to which I was going to add text later for the titles, etc.
    The width of the artboard takes into account the size of the spine, which is calculated for each book since they have different number of pages.
    I've uploaded the file if you want to take a look at it as it doesn't make much sense to me. The file can be downloaded from here:
    http://www.ezref.com/wp-content/uploads/Book%20Cover%20-%208.5%20x11.ai
    Thanks for your time and help.

  • Jagged edge around edge of graphic

    This is a multi-part message in MIME format.
    ------=_NextPart_000_0010_01C69542.BF067750
    Content-Type: text/plain;
    charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    I am creating an arrow with a transparent background,
    however, there is =
    a jagged edge or fuzz around the graphic. Any ideas how to
    remove this?
    Scott
    ------=_NextPart_000_0010_01C69542.BF067750
    Content-Type: text/html;
    charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN">
    <HTML><HEAD>
    <META http-equiv=3DContent-Type content=3D"text/html; =
    charset=3Diso-8859-1">
    <META content=3D"MSHTML 6.00.2900.2912"
    name=3DGENERATOR>
    <STYLE></STYLE>
    </HEAD>
    <BODY bgColor=3D#ffffff>
    <DIV><FONT face=3DArial size=3D2>I am creating an
    arrow with a =
    transparent=20
    background, however, there is a jagged edge or fuzz around
    the graphic. =
    Any=20
    ideas how to remove this?</FONT></DIV>
    <DIV><FONT face=3DArial
    size=3D2></FONT> </DIV>
    <DIV><FONT face=3DArial
    size=3D2>Scott</FONT></DIV></BODY></HTML>
    ------=_NextPart_000_0010_01C69542.BF067750--

    Scott Powell wrote:
    > I am creating an arrow with a transparent background,
    however, there is a jagged edge or fuzz around the graphic. Any
    ideas how to remove this?
    >
    > Scott
    Draw the arrow on a canvas colored to match the background of
    the page
    you will be using it on, then export with Index Transparency.
    Linda Rathgeber [PVII] **Adobe Community Expert-Fireworks**
    http://www.projectseven.com
    Fireworks Newsgroup:
    news://forums.projectseven.com/fireworks/
    CSS Newsgroup: news://forums.projectseven.com/css/
    Design Aid Kits:
    http://www.webdevbiz.com/pwf/index.cfm

  • Blend mode - removing halo around edge of alpha??

    This is a complicated question so I'm hoping there are some real Pros here.
    I have a final image of my image to which I want to apply an alpha as a mask of an adjustment layer.
    The image and the alpha have come out of 3ds Max. The problem is that there is a halo around the edge of the mask. This is caused due to transparency at the border of the alpha. I don't know how to get around this.
    I was told that there may be a way to do it by dividing the alpha. I see that Photoshop CS5 has a divide blend mode. I don't have CS5. Does anyone know if this solves this issue? Or any other solutions
    I've attached the render passes that I'm working with and below is an image of the problem once the alpha is applied and the hue/saturation is altered.
    http://www.fileswap.com/dl/LQmX9s/Passes.zip.html
    http://s919.photobucket.com/albums/ad34/elaihphotography/?action=view&current=Example-Clos eupObjectIDHalo.jpg

    Thanks MTSTUNER,
    That's a very interesting approach and something I hadn't considered before. I'm getting slightly different results in the look though. Is there a way to fix the alpha and mask a straight Hue/Saturation layer instead? Do you know if the divide blend mode in CS5 would help?

  • Blank/blac​k 3/4 inch ribbon around edge of monitor

    Recieved HP 23 all in one last Wednesday and the sceen displays were occupying the entire monitor, Now the displays are reduced so that there is 3/4 inch of blank/black screen all the way around the monitor. Screen resolution is set to 1920X1080. Spoke w/MS and they do not think it is a Windows 8.1 issue.

    Hello , I have read your post on how your desktop monitor produces a loss of signal, or the screen goes black, and I would be happy to help you! Since you mentioned that you have completed all of the steps in this docuemnt, and the issue continues, please contact our technical support for further assistance in this matter by clicking the link below to get the support number for your region.
    www.hp.com/contacthp/
    I hope this helps!
    Regards

  • Fading around edge of images [cs3]

    I've spent a fair bit of time a few times, using the eraser tool and soft brush to `fade' around the edges of photos so they don't appear hard but blend with the background in some smooth way near the edges.
    I'm pretty sure this could be done using some kind of masking.  I don't understand much about masking but wondered if someone might walk me through it, at least in broad outline.
    I'm hoping I could create some kind of mask that could be used over any image of the right size.  So that, if I had a bunch of same sized images I could make one mask and then tranfer the layer to all the pictures.
    I'd like the end result to look something like the quicky sloppy job <ahref="www.jtan.com/~reader/vu/disp.cgi"> <b>HERE</b> </a>
    where the top picture is unedited and I've  used the big soft eraser around the edges of the bottom picture.
    [ NOTE:
    I can't seem to master the new controls on this forum so not sure how to enter a url and make it clickable... one failed attempt above.
    Here is the site to copy and paste: www.jtan.com/~reader/vu/disp.cgi
    Once more usging the insert tool:

    if you are going to save your same sized picture in different names, like pic1, pic2 and so on:
    drag all your pic to your main PSD
    in the layer pallate, select them all
    create folder for them
    ctrl+click on one of the layers
    you get the selection
    select the folder
    hit the create mask, now all your PICs are masked
    select the mask and unlick the link sign
    ctrl+T to control the size of the mask
    feather it or blur it
    thats it , you got one mask for all layers. you can delete, add and do anaything with one mask.
    the idea of the mask is:
    black and white, imagine you are in a dark room. you do not see any thing, since you turn on your tourch you see the ojects that stay under the spot light.
    cheers

  • Really bad service around Edge offer and why I am likely leaving

    This post is just me venting and giving my feedback to Verizon on something I feel was handled really poorly.  Last May I switched my entire family off Iphones for Androids (5 phones) and it has been a disaster.  We have tons of group texting issues, screens going black and app problems.  i feel like I am in constant support mode for my three kids doing soft resets just to keep them working.  I called Verizon seeking help, knowing we were out of cycle for an upgrade, but I just wanted to understand my options for getting back to Iphones.  The rep told me about the Edge program where we could switch to the latest Iphones and effectively pay an extra $2 a month after reducing the line access fee by $25.  I was very excited about this, but wanted to talk with the family to make sure I knew which phones/ colors they all wanted.  The rep promised to call me back that night at 7:30 to complete the action.  I talked it through with them and they were all very excited. I didn't get a call that night so I called back in the next morning.  I was informed that the rep had requested approval to get me on the early edge program and that I was not eligible.  I was told there was a reminder for that rep (Christina) to call me back at 3.  I was pretty confused as Edge was offered to me yesterday with none of this conversation about eligibility.  I decided to wait for a call back so that Christina could hopefully finish what she had offered.  Shockingly, I didn't get a call back so I called in at 4 and was told that I wasn't eligible for early edge even though the system showed I was an awesome customer with more than 4 years of never missing a $270 payment.  Because of this sterling record they offered to put one phone on edge for me.  Really?  You want me to go back to one of my three children and tell them they are the chosen one?  After much discussion and putting me on hold to talk to supervisors they informed me that this was all they could do.  I have now gotten my entire family really excited about going back to Iphones and have to tell them it isn't true.  I was a 0 for switching them, then I was the hero, now I am like -20.  Switching to another carrier is likely my cheapest option to fix this.

    You have 5 phones on 2 year contracts less than one year.  It is expected you should complete the contracts in order to upgrade to new phones.  
    The phones are yours.  If they are faulty, you have the option to have them repaired or replaced under the one year warranty.
    If you don't like the phones, you can replace them at your own expense.  Switching phones, on any carrier, means you buy a new phone at full price and sell the existing phone for what ever you can get for it. 
    I Don't know why a CS associate would even try to get you out of 2 year contract less than a year in.  I've never heard of anyone getting out that early.  Even if they let you out early, the phones offered are usually limited to two android model phones.
    SO, yes, your best option is to bail.  Plan on buying phones at full price, insured with AppleCare plus, direct from Apple so you can move carriers again at will.

  • I can not run animation iframe in Edge

    English:
    Hello everyone, sorry for my English, but I'm an Italian guy. I have been trying for days to enter an interactive animation with the mouse on adobe edge, but I can not. Adobe muse I just click enter html code, I copy and paste the code that is this: <iframe src = "linkanimazione.html" width = "1280" height = "720" frameborder = "0" scrolling = "no"> </ iframe> and it works great, but I have to create the button at the edge, because I have to insert a voice audio when you hover over with the mouse before opening the animation. Why in muse so simple, and in edge seems so complex? No practical code, please can someone tell me very clearly how to do? In the net I found a little and I could not make it work.
    My button that I should create is composed as follows: background image, roll image when you hover over an item with the mouse and audio ... then when you clik on the roll you open a lightbox with animation iframe interactive with the mouse.
    Thank you very much indeed
    Italian:
    Ciao a tutti, scusate per il mio inglese, ma sono un ragazzo italiano. Sto provando da giorni, ad inserire un animazione interattiva con il mouse su adobe edge, ma non ci riesco. In adobe muse mi basta cliccare su inserisci codice html, copio e incollo il codice che è questo: <iframe src="linkanimazione.html" width="1280" height="720" frameborder="0" scrolling="no"></iframe> e funziona benissimo, ma sono costretto a creare il bottone in edge, perche devo inserire anche una voce audio quando si passa sopra con il mouse prima di aprire l'animazione. Perchè in muse cosi semplice, ed in edge sembra cosi complesso? Non sono pratico di codici :(, per favore qualcuno mi può dire in modo molto chiaro come fare? In rete ho trovato poco e non sono riuscito a farlo funzionare.
    Il mio bottone che dovrei creare è cosi composto: immagine di sfondo, immagine roll quando si passa sopra con il mouse e una voce audio... poi quando si clikka sull'immagine roll si apre un lightbox con l'animazione iframe interattiva con il mouse.
    Grazie mille davvero

    Hello, thank you, I did some tests on the Stage with creationComplete compositionReady and copying and pasting the code of the button: sym. $ ("PLACEHOLDER"). Append ('<iframe src = "http://www.bbc.com/" height = "224px" width = "550px" frameborder = "0" scrolling = "no"> </ iframe> '); but does not work. Nothing happens to the mouse click. Would you be so kind as to explain to me how to do it in a simple way, without possibly assume no passage? I know very little code html and I'm learning just Edge Animate. Thank you very much

  • I was wondering how the advertised 10G multiple line plan that is running now is different from my current plan. Basically, why am I paying more now for 4G of data when Verizon is saying I can get 10 for the same price basically.

    NM

    Most of the advertisements running now are for Edge. You get discounts for having a smart phone on Edge based on the data package you have. What sucks is that most of the time they advertise a certain price for the monthly service and that is true but what they don't say is you add the Edge payments to that and most of the time it is around the same price as without Edge.
    If you think about this though, say you get a phone that is $24.99/month with Edge and you share 10GB which gives you a $25 discount, the phone is basically free and nothing is due at checkout. If you get a 2 year contract with that phone you pay the 2 year price of the phone and pay the same amount monthly.

  • Can Text run in line with circle shape?

    I am working on a table seating plan and want the text to run in line (around) the inner edge of the circle. Can this be done??

    PeterBreis0807 wrote:
    Indeed I will, for the benefit of +you amateurs+ who wouldn't know the difference between a drawing program and a burnt stick.
    I perfectly knows the difference between ArtText and vectorial programs.
    Just wish to say that ArtText is able to fit the needs of many users even if so called 'professionals' may laugh.
    During years, so called 'professionals' where laughing in front of AppleWorks
    Yvan KOENIG (VALLAURIS, France) vendredi 11 septembre 2009 10:11:11

Maybe you are looking for

  • How can I transfer files from one pc the the other pc?

    I've purchased another pc recently and want to transfer my items such as my music and film libraries to my new pc. I want to use HomeShare, and have enabled homeshare on the new pc, and verified it with my apple ID. However, I had to delete my other

  • Is there a way to view the web history after it's been cleared from the history tab?

    Is there a way to view the web history after it's been cleared from the history tab?

  • Query to find revenue of a bank

    We have loan datamart and account datamart. For joining the two fact tables of loan and account, we use customer table as conformed dimension.we need to calculate the revenue,assets and liability of the bank.can anyone help us with this?? loan datama

  • Making P2P Video Chat with FMS

    Hi, I'm trying to make a P2P video chat application with Flash Builder 4.5 and Flash Media Server 4.5. First, I've tried a simple sample application using Cirrus(Stratus). It worked very well! NetConnection -> NetGroup -> 2 NetStreams -> netstream pl

  • Screen Saver Randomness

    Hello! I've been having a problem - more of an annoyance - that the screensaver I set in System Preferences will, at seemingly random times, switch away from my iPhoto slideshow to something else, usually another album, but sometimes to the Computer