我还是java新手,我很难理解所有课程。 现在,我被困在为我的迷宫添加一个keyListener。我们试图添加一个内部类w / c实现一个KeyListener,但它不起作用。这是我们尝试在JFram中添加的keyListener。嗯,是的,它很长(我想首先没有问题)。如果它真的有用,我试着有一些打印声明,但即使打印也不会出现。我也尝试在我的JFrame中使用requestFocus,但没有运气......
public class Play implements KeyListener{
public void keyPressed (KeyEvent e){
int i=0,j=0;
for(int a = 0; i<10;i++){
for(int b=0; j<10; j++){
if(getMazePlan()[a][b] ==2){
i=a;j=b;break;
}}}
if (e.getKeyCode() == KeyEvent.VK_UP){
if(i-1 >=0 && i-1<=9)
{ if(getMazePlan()[i-1][j] !=1)
{
setMazePlan1(0, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i,j);
mazeLabel[i][j].repaint();
i= i-1;
setMazePlan1(2, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i,j);
mazeLabel[i][j].repaint();
}
}
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN){
if(i+1 >=0 && i+1<=9)
{ if(getMazePlan()[i+1][j] !=1)
{
setMazePlan1(0, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i, j);
mazeLabel[i][j].repaint();
i= i+1;
setMazePlan1(2, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i, j);
mazeLabel[i][j].repaint();
}
}
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT){
if(j-1 >=0 && j-1<=9)
{ if(getMazePlan()[i][j-1] !=1)
{
setMazePlan1(0, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i, j);
mazeLabel[i][j].repaint();
j= j-1;
setMazePlan1(2, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i, j);
mazeLabel[i][j].repaint();
}
}
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
if(j+1 >=0 && j+1<=9)
{ if(getMazePlan()[i][j+1] !=1)
{
setMazePlan1(0, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i, j);
mazeLabel[i][j].repaint();
j= j+1;
setMazePlan1(2, i,j);
mazeLabel[i][j].setPic(getMazePlan(), i, j);
mazeLabel[i][j].repaint();
}
}
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}