import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.sound.sampled.*;
import java.util.ArrayList;
public class Board extends JPanel implements ActionListener
{
Timer time;
Image Border;
Image Dude;
Image Road;
Image GZombie;
Image RZombie;
Image BZombie;
MovingPiece player;
public Board()
{
//set this window to be the one receiving keystrokes
addKeyListener(new AL());
setFocusable(true);
ImageIcon dude = new ImageIcon("Dude.png"); //player
Dude=dude.getImage();
// Cx and Cy are changed in move methods, they are change in (x/y)
// X Y W H CxCy Speed Image
player=new MovingPiece(200,300,50,50,0,0,2,Dude);
time=new Timer(5,this);
time.start();
}
public void actionPerformed(ActionEvent e){
player.setX(player.getX() + player.getCx()); //adds my x to my change in x
player.setY(player.getY() + player.getCy()); //im sure u can figure this one out...
//redraw the screen
repaint();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(player.getImage(),player.getX(),player.getY(),null); //draw player
}
//the key listener, it is a private class inside of the Board class
private class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
System.out.println(key); //*THIS IS WHAT WONT RUN*
if(key==KeyEvent.VK_W){player.moveUp();} //this changes my cy to be -speed which is -2
if(key==KeyEvent.VK_A){player.moveDown();} //this changes my cy to be speed which is 2
if(key==KeyEvent.VK_S){player.moveLeft();} //I made this simple.. this is cx
if(key==KeyEvent.VK_D){player.moveRight();} //take a guess.
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key==KeyEvent.VK_W){player.setCy(0);} //stops my changes in y so I don't move up/down
if(key==KeyEvent.VK_A){player.setCx(0);} //quite repetitive.
if(key==KeyEvent.VK_S){player.setCy(0);}
if(key==KeyEvent.VK_D){player.setCx(0);}
}
}
}
基本上我的keyadapter不会运行。打印什么钥匙并不重要。 但它是一个指示器,用于查看方法是否正在运行,或者问题是否与我的移动方法有关。 因为它不打印,所以方法本身没有运行。因此,这不是我的移动方法。它必须是这个适配器。我只是想知道为什么它不起作用。我设置了焦点,这是所有其他论坛所要做的。所以。请帮忙。提前谢谢