gpt4 book ai didi

java - KeyListener 事件显然没有在 Java 小程序中触发

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:27 26 4
gpt4 key购买 nike

我刚刚开始学习编写小程序和一般的 Java GUI,我正在尝试制作一个简单的游戏。目前,我有主类(游戏)和玩家类(玩家),我有玩家在屏幕上绘制,但我正在努力让关键事件正常工作,感谢任何帮助!

播放器图像显示得很好,但当我按下一个键时位置根本没有改变。

编辑:为播放器发布的错误代码,已更新

游戏.java:

public class Game extends Applet {

Player player;

@Override
public void init() {
player = new Player(this);
this.setSize(800, 600);
addKeyListener(player);
}

@Override
public void paint(Graphics g) {
player.paint(g);
}



}

播放器.java:

public class Player implements KeyListener {

Game game;
Image image;
int x;
int y;

public Player(Game game) {
this.game = game;
x = 0;
y = 0;
image = game.getImage(game.getCodeBase(), "images/Player.png");
}

public void paint(Graphics g) {
g.drawImage(image, x, y, game);
}

@Override
public void keyTyped(KeyEvent e) {
return;
}

@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_A:
x -= 1;
break;
case KeyEvent.VK_D:
x += 1;
break;
case KeyEvent.VK_S:
y += 1;
break;
case KeyEvent.VK_W:
y -= 1;
break;
}
game.repaint();
}

@Override
public void keyReleased(KeyEvent e) {
return;
}
}

最佳答案

面板可能没有焦点,或者不可聚焦。


试试这段代码。我将键更改为左/右/上/下箭头。为简单起见,我将其保留为基于 AWT 的小程序。

// <applet code='Game' width=400 height=100></applet>
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Game extends Applet implements KeyListener {

Player player;

@Override
public void init() {
player = new Player(getImage(32));
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}

@Override
public void paint(Graphics g) {
player.paint(g);
}

public Image getImage(int size) {
Image img = createImage(size,size);
Graphics g = img.getGraphics();
g.setColor(Color.RED);
g.fillRect(0,0,size,size);

g.dispose();

return img;
}

@Override
public void keyTyped(KeyEvent e) {
return;
}

@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
player.x -= 1;
break;
case KeyEvent.VK_RIGHT:
player.x += 1;
break;
case KeyEvent.VK_DOWN:
player.y += 1;
break;
case KeyEvent.VK_UP:
player.y -= 1;
break;
}
repaint();
}

@Override
public void keyReleased(KeyEvent e) {
return;
}
}

class Player {

Image image;
int x;
int y;

public Player(Image image) {
x = 0;
y = 0;
this.image = image;
}

public void paint(Graphics g) {
g.drawImage(image, x, y, null);
}

}

关于java - KeyListener 事件显然没有在 Java 小程序中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9504906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com