我希望将吃豆人的JPEG图像添加到空布局JPanel中,以便我可以使用密钥侦听器来移动图像。这是我到目前为止的代码:
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);
}
}
图像出现在屏幕上,但不移动。
您需要使用键盲而不是AWT KeyEvents,因为AWT KeyEvent需要焦点才能收听事件,而且xCoor = xCoor--;
不像您期望的那样工作,您应该使用xCoor--;
或xCoor = xCoor-1;
。这是您可以为所有箭头键编写up
键的示例......
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=30;
static int yCoor;
public static class PacmanPanel extends JPanel {
public PacmanPanel() {
this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "doup");
this.getActionMap().put("doup", new AbstractAction("doup") {
public void actionPerformed(ActionEvent evt) {
xCoor--;
yCoor = yCoor;
repaint();
}
}
);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(pacman, xCoor, yCoor, null);
}
}
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");
PacmanPanel mainPanel = new PacmanPanel();
window.setContentPane(mainPanel);
window.setSize(600, 450);
window.setLocation(350, 150);
window.setVisible(true);
}
}
关键事件仅调度到具有焦点的组件。默认情况下,JPanel 不可聚焦,因此它永远不会接收关键事件。
更好的方法是使用 KeyBinding,即使事件没有焦点,它也可以响应事件。请参阅使用键盘的动作以获取更多信息和工作示例。