Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

I need help with Java Applet?

I need help updating the position of my moving circle in my Java Applet. Whenever I try to make it move faster it doesn't work. I need to be able to adjust the speed of the moving circle. What is wrong with my code?

import java.awt.*;

import java.applet.Applet;

public class phys extends Applet{

public static int height = 500;

public static int width = 500;

public static int radius = 126;

public static int y = 0;

public static int x = 0;

public static int xVel = 15;

public static int yVel = 15;

public void paint(Graphics g){

setBackground(Color.white);

setForeground(Color.black);

g.drawOval((width / 2 - radius), (height / 2 - radius), 2 * radius, 2 * radius);

g.drawOval(x, y, 5, 5);

if(x == 500 && y == 500){x = 0; y = 0;}

try{

Thread.currentThread().sleep(1000 / 60);

repaint();

}catch(Exception e){}

}

}

2 Answers

Relevance
  • 8 years ago
    Favorite Answer

    1. You don't want to call sleep() from within your paint() method. This won't work. What you need to do is to setup a Swing Timer object to call your Applet object periodically to give it some time to move your x and y coordinates. Once you change x and y, call repaint() and this will cause your paint() method to be called.

    So, you can totally delete the try-sleep-catch from your paint method.

    2. You'll need to create a Swing Timer. Here is a tutorial on that:

    http://docs.oracle.com/javase/tutorial/uiswing/mis...

    For the Timer to work, it'll have to have an ActionListener. Your Applet will work fine as an ActionListener. What you can do is to have your Applet implement the ActionListener interface. You'll also have to implement an actionPerformed() method. This method is what will be called every time that the Timer fires. You can change x and y and call repaint() to have the circles redrawn.

    3. I think that ideally, you would have a Circle class and have two instances of Circle and each would have its own x, y, and radius instance variables (not static) so that each Circle could have its own data independent of the other one.

    I hope that this has helped you.

  • ?
    Lv 7
    8 years ago

    Change sleep function inside value

    Thread.currentThread().sleep(1000 / 60);

Still have questions? Get your answers by asking now.