I have been following some tutorials, trying to get into programming in Java and so far all has worked well. The problem I have now stumbled upon is, I am not able to move my image around in my window with the arrow keys after proceeding with the tutorials into threads. I have followed the code, in a manner I thought was precise, and yet, my image will not move with the arrow keys being pressed down. Can anyone point out what I’m doing wrong?
package javagame;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class JavaGame extends JFrame implements Runnable{
int x, y, xDirection, yDirection;
private Image dbImage;
private Graphics dbg;
Image face;
public void run(){
try{
while(true){
move();
Thread.sleep(5);
}
}
catch(Exception e){
System.out.println("error...");
}
}
// handle movement thread.
public void move() {
x += xDirection;
y += yDirection;
if (x <= 0);
x = 0;
if (x >= 50);
x = 50;
if (y <= 0);
y = 0;
if (y >= 50);
y = 50;
}
// set up the directional movement variables of the player.
public void setXDirection(int xdir) {
xDirection = xdir;
}
public void setYDirection(int ydir) {
yDirection = ydir;
}
// handle key input.
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
// handle arrow key movement.
if (keyCode == e.VK_LEFT) {
setXDirection(-1);
}
if (keyCode == e.VK_RIGHT) {
setXDirection(+1);
}
if (keyCode == e.VK_UP) {
setYDirection(-1);
}
if (keyCode == e.VK_DOWN) {
setYDirection(+1);
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
setXDirection(0);
}
if (keyCode == e.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == e.VK_UP) {
setYDirection(0);
}
if (keyCode == e.VK_DOWN) {
setYDirection(0);
}
}
}
// handle the window class.
public JavaGame() {
// load images.
ImageIcon i = new ImageIcon(
"C:/Users/Me/workspace/JavaGame/src/javagame/face.png");
face = i.getImage();
// game properties.
addKeyListener(new AL());
setLocation(400, 300);
setTitle("JavaGame");
setSize(256, 256);
setResizable(false);
setVisible(true);
setBackground(Color.RED);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 50;
y = 50;
}
// handle graphics input.
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
// draw and refresh the image.
g.setColor(Color.RED);
g.drawImage(face, x, y, this);
repaint();
}
public static void main(String[] args) {
JavaGame jg = new JavaGame();
// Threads
Thread t1 = new Thread(jg);
t1.start();
}
}
I was able to move the object earlier using the following code format.
if (x >= 200);
x = 200;
else
x += 5;
This, however was not best for the style I wanted to do. Where did I go wrong?