I'm practicing some simple techniques with Java swing games, to learn the basics. Right now I'm practicing how to move a sprite... but it's not working! whhyyyy
Here is what I've come up with so far (Main class):
public class GraphicsPracticeDrawing extends JPanel implements Runnable{
private CoinSprite coin2;
private Thread animate;
private final int DELAY = 25;
public GraphicsPracticeDrawing(){
setBackground(Color.BLACK);
this.addKeyListener(new InputHandler());
Initialize();
animate = new Thread(this);
animate.start();
}
public void Initialize(){
coin2 = new CoinSprite("images/coin.gif", 25, 25);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(coin2.getImage(), coin2.getX(), coin2.getY(), null);
}
@Override
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while(true){
coin2.move2(); //move the 2nd coin based on the inputHandler
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if(sleep < 0)
sleep = 2;
try{
Thread.sleep(sleep);
} catch(InterruptedException e){
System.out.println("Animation interrupted!");
}
beforeTime = System.currentTimeMillis();
}
}
/*
* create a inner class to handle key inputs via the CoinSprite class
*/
private class InputHandler extends KeyAdapter{
public void keyPressed(KeyEvent e) {
coin2.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
coin2.keyReleased(e);
}
}
}
and for my CoinSprite class:
public class CoinSprite {
private BufferedImage img;
private int speedKeyX, speedKeyY;
public CoinSprite(){ }
public CoinSprite(String fileLoc, int x, int y){
try{
this.img = ImageIO.read(new File(fileLoc));
} catch (IOException e){
System.out.println("Can't load file!");
}
this.x = x;
this.y = y;
}
/*
* move the sprite based on key inputs
*/
public void move2() {
this.x += this.speedKeyX;
this.y += this.speedKeyY;
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
speedKeyX = -1; //when move is, called change the speed
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
speedKeyX = 1;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT){
speedKeyX = 0;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
speedKeyX = 0;
}
}
//GETTERS
public BufferedImage getImage(){ return this.img; }
public int getX(){ return this.x; }
public int getY(){ return this.y; }
//SETTERS
public void setX(int x){ this.x = x; }
public void setY(int y){ this.y = y; }
}
When I run the game and press left and right the sprite wont move! I don't know why...