我有以下代码(我在扩展frame.add(new LevelPanel())
的主要方法中使用了JFrame
。出于某种原因,KeyListener
的代码与其他人的代码完全一样,但是却无法识别任何内容。
当我按下一个键时,它至少应该打印出“ Got here”(不是)。该代码确实会打印面板,但是该面板对我按的任何键均无反应。
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");
}
}
}
最佳答案
KeyListener
是一个善变的情妇,我建议您避免使用它们,而赞成key bindingsKeyListener
仅在以下情况下触发事件:1-组件可聚焦并且2-组件具有焦点。按键绑定使您可以绕开此限制。
如果必须使用KeyListener
,请先在setFocusable(true)
上调用LevelPanel
,然后再调用requestFocusInWindow
。
关于java - 即使面板打印,KeyListener也无法使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13559283/