I am looking to add a JPEG image of Pacman to a null layout JPanel so that I can use a key listener to move the image. Here's the code I have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
public class PacmanCharacterMovement2{
static BufferedImage pacman;
static int xCoor;
static int yCoor;
public static class PacmanPanel extends JPanel implements KeyListener {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(pacman, xCoor, yCoor, null);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
xCoor = xCoor--;
yCoor = yCoor;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
xCoor = xCoor++;
yCoor = yCoor;
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
xCoor = xCoor;
yCoor = yCoor--;
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
xCoor = xCoor;
yCoor = yCoor++;
}
else{}
repaint();
}
public void keyReleased(KeyEvent e) {
}
}
public static void main(String[] agrs){
try {
pacman = ImageIO.read(new File("PacmanCharacter2.jpg"));
} catch (IOException e) {}
xCoor = 30;
yCoor = 30;
JFrame window = new JFrame ("Pacman Movement");
JPanel pacmanPanel = new JPanel ();
pacmanPanel.setLayout(null);
PacmanPanel mainPanel = new PacmanPanel();
window.setContentPane(mainPanel);
window.setSize(600,450);
window.setLocation(350,150);
window.setVisible(true);
}
}
The image appears on the screen but it does not move.
you need to use key blind instead awt keyevents because awt keyevent required focus to listen to event .and also
xCoor = xCoor--;
not work like u expected you should usexCoor--;
orxCoor = xCoor-1;
. this is example forup
key you can write for all arrow keys ...