我有以下代码(我frame.add(new LevelPanel())
在我的 main 方法中执行 extends JFrame
。出于某种原因,此代码对于KeyListener
其他人来说正是它的样子,但它不识别任何东西。
当我按下一个键时,它至少应该打印出“到这里”(它没有)。该代码确实打印了面板,但面板对我按下的任何键都没有反应。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* Items represent the things in the level that can be picked up.
* Subclasses: Gem
*
* @author Tim Ochsner
* @version 1.0 11/18/2012
*/
public class LevelPanel extends JPanel {
private Game game;
private Level level;
private Player player;
private char[][] table =
{{'p', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f'},
{'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f'},
{'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f'},
{'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'w', 'w', 'w', 'f', 'f', 'f', 'f'},
{'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f'},
{'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f'},
{'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f'},
{'w', 'f', 'f', 'f', 'w', 'w', 'w', 'w', 'w', 'f', 'f', 'f', 'f', 'f', 'f'},
{'w', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f'},
{'w', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f'},
{'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f'},
{'f', 'f', 'f', 'f', 'f', 'f', 'w', 'w', 'w', 'w', 'f', 'f', 'w', 'w', 'f'},
{'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f', 'f', 'w', 'f'},
{'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f'},
{'w', 'w', 'w', 'w', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f'}};
public LevelPanel(Game game)
{
this.game = game;
player = game.getPlayer();
level = new Level(game, table);
setBackground(Color.WHITE);
addKeyListener(new ArrowListener());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
level.draw(g);
}
public class ArrowListener implements KeyListener {
public void keyPressed(KeyEvent e) {
System.out.println("Got here");
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (!(player.getCol() == 14) && level.getTileLayout()[player.getRow() + 1][player.getCol()].isPassable()) {
System.out.println("Got here");
player.move(player.getRow() + 1, player.getCol());
table[player.getRow()][player.getCol()] = 'f';
table[player.getRow() + 1][player.getCol()] = 'p';
}
}
}
public void keyReleased(KeyEvent e) {
System.out.println("Got here");
}
public void keyTyped(KeyEvent arg0) {
System.out.println("Got here");
}
}
}