I have three images that I want to cycle through once a KeyEvent is hit. But, since the paint method is constantly repainting, my images get cycled through pretty fast. So far, the only thing that’s worked is if I make the thread sleep for a longer period. Which messes up everything else.
This code below isn’t what I’m working on but it has the basic principles. The colors get updated everytime the thread wakes up. How do I slow the colors down only. If you increase the number inside thread.sleep() to 300, you’ll get what I’m trying to do.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
public class TheApplet extends Applet implements KeyListener, Runnable{
public int x = 20;
public int y = 20;
public int dx = 5;
public Random r = new Random();
public Random r2 = new Random();
public Random r3 = new Random();
boolean change = false;
boolean keydown = false;
public void init(){
setSize(800, 600);
setFocusable(true);
addKeyListener(this);
}
public void start(){
Thread thread = new Thread(this);
thread.start();
}
public void run(){
int counter = 0;
while(true){
if(keydown && counter <= 0) x+=dx;
counter--;
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paint(Graphics g){
if(change){
int RandomNum = r.nextInt(200);
int RandomNum2 = r2.nextInt(200);
int RandomNum3 = r3.nextInt(200);
g.setColor(new Color(RandomNum, RandomNum2, RandomNum3));}
g.fillRect(x, y, 40, 40);
}
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
keydown=true;
change = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
keydown=false;
change = false;
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}