[英]KeyListener doesn't respond
I have written some code that makes labyrinth and fills the JPanel
with my figures Wall
, Player
, Road
and Gate
. 我已经编写了一些使迷宫产生的代码,并用我的人物
Wall
, Player
, Road
和Gate
填充了JPanel
。 I want to move the player by pressing the keys W , A , S , D . 我想通过按W , A , S , D键移动播放器。
The frame gets drawn but the player is not moving: 框架被绘制,但播放器没有移动:
Sprite[][] spr = fr.read();
int x1 = fr.row;
int y1 = fr.col;
fr.close();
GameFrame gf = new GameFrame(spr, x1, y1);
x1 = (x1 * 20) + 30;
y1 = (y1 * 20);
JFrame frame = new JFrame();
frame.setTitle("Lab");
frame.setSize(new Dimension(y1, x1));
frame.setPreferredSize(new Dimension(y1, x1));
frame.addKeyListener(gf);
frame.setFocusable(true);
frame.add(gf);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
public void paint(Graphics g) {
int a13 = 5;
int a14 = 5;
Player pl = new Player();
super.paintComponent(g);
for (int i = 0; i < i1; i++) {
for (int i0 = 0; i0 < i2; i0++) {
Sprite currentSpr1 = sprites[i][i0];
X = currentSpr1.setXCoord(i);
Y = currentSpr1.setYCoord(i0);
H = currentSpr1.setHeight();
W = currentSpr1.setWidth();
if (currentSpr1 == pl) {
addKeyListener(this);
}
currentSpr1.YourPaint(g, X, Y, H, W);
}
}
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_W) {
Y = Y - 20;
System.out.print("lol");
repaint();
}
if (c == KeyEvent.VK_S) {
Y = Y + 20;
//repaint();
}
if (c == KeyEvent.VK_D) {
X = X + 20;
//repaint();
}
if (c == KeyEvent.VK_A) {
X = X - 20;
//repaint();
}
//if (sprite instanceof Wall){
//}*/
}
Well, it's a bit hard to understand your code, but firstly: 好了,很难理解您的代码,但是首先:
In your keyPressed method you're incrementing X or Y, but in your update method you're resetting X and Y, so this will have no effect. 在keyPressed方法中,您将递增X或Y,但在更新方法中,您将重置X和Y,因此这将无效。
And what's gf? 什么是gf? Is it the class above.
是上面的课程吗? You should add "this" as a keylistener.
您应该将“ this”添加为键侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.