I am new to java programming and I am trying to move the object using the arrow keys using KeyListener but the object does not move. I've googled it but I can't seem to figure out where I'm going wrong. I was able to move the object on it's own but nothing happens after I set the velocity to 0 and added the keyListener. Please check my code and help me figure out what I did wrong.
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Games extends JFrame{
public Games(){
super.setTitle("Sokoban");
super.setSize(600, 600);
super.setLocation(400, 300);
super.setResizable(false);
super.add(new Contents());
super.setVisible(true);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setLayout(new BorderLayout());
}
public static void main(String[] args) {
new Games();
}
}import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
public class Contents extends JPanel implements ActionListener, KeyListener {
private Image person;
private int x=0, y= 0;
private int speedXCordinate= 0, speedYCordinate= 0;
Timer time = new Timer(7, this);
public Contents(){
super.setDoubleBuffered(true);
time.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
@Override
public void paintComponent(Graphics g){
ImageIcon p = new ImageIcon(this.getClass().getResource("person.jpeg"));
Graphics2D q = (Graphics2D) g;
person = p.getImage();
q.drawImage(person, x, y, this);
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
x+= speedXCordinate;
y+=speedYCordinate;
}
public void up(){
speedXCordinate=0;
speedYCordinate=-1;
}
public void down(){
speedXCordinate=0;
speedYCordinate=1;
}
public void left(){
speedXCordinate=-1;
speedYCordinate=0;
}
public void right(){
speedYCordinate=1;
speedYCordinate=0;
}
@Override
public void keyTyped(KeyEvent e) { . //method for moving object
int c= e.getKeyCode();
if( c == KeyEvent.VK_LEFT){
left();
}
if(c==KeyEvent.VK_RIGHT){
right();
}
if(c==KeyEvent.VK_UP){
up();
}
if(c==KeyEvent.VK_DOWN){
down();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
speedXCordinate=0;
speedYCordinate=0;
}
}