How to convert thread.sleep() into a timer in an Applet
Since I have used the thread.sleep() method, my graphics is updating way to slowly. How would I convert this into a timer?
The point of the applet is just to move the black dot around the screen based on the arrow keys that are pressed. (I am eventually going to make this into a snake game, but am taking it one step at a time.)
Code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.applet.*;
import java.util.*;
import static java.lang.System.*;
public class SnakeSimple extends Applet implements KeyListener{
int x = 0;
int y = 0;
byte direction;
final byte UP = 1;
final byte RIGHT = 2;
final byte DOWN = 3;
final byte LEFT = 4;
public void init() {
x = 100;
y = 100;
addKeyListener(this);
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillOval(x, y, 10, 10);
run();
}
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(direction==UP){
y-=10;
}
if(direction==DOWN){
y+=10;
}
if(direction==LEFT){
x-=10;
}
if(direction==RIGHT){
x+=10;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==37){
direction = LEFT;
}
if(e.getKeyCode()==38){
direction = UP;
}
if(e.getKeyCode()==39){
direction = RIGHT;
}
if(e.getKeyCode()==40){
direction = DOWN;
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Re: How to convert thread.sleep() into a timer in an Applet
In the init() method, create a Swing Timer with the delay you want and with an ActionListener that calls the run() method. Delete the Thread.sleep from the run method. After the Timer is created, call its start() method. Don't call the run() method from paint().
Re: How to convert thread.sleep() into a timer in an Applet
On top of what dlorde said, the reason things are running so slowly is that you're blocking the EDT by sleeping from your paint method, which is called by the EDT. The EDT controls things like events and painting, so blocking that thread will cause those things to slow down. If you have no idea what I'm talking about, google is your friend. Hint: EDT stands for "Event Dispatching Thread".
A Swing Timer (and switching to JApplet) is the way to go. But just to demonstrate the point, if you put that run() method in a forever loop in another Thread, I think you'd see the effect you're looking for.
PS- I do want to congratulate you on your "one thing at a time" approach. That's definitely the way to go.