我正在尝试获得一些基本的键盘输入功能,例如箭头键。但是,我尝试的任何方法似乎都不起作用,我一直在使用 KeyListener 接口,检查输入的 JPanel 获得焦点,并且似乎没有错误。
public class PlayField extends JPanel implements KeyListener
{
private SpelModel mijnmodel;
private boolean rechts = false;
private boolean links = false;
public PlayField(SpelModel mijnmodelArg)
{
setBackground(Color.WHITE);
mijnmodel = mijnmodelArg;
this.setFocusable(true);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); //some methods that i've taken out of the example
drawStones(g,mijnmodel.getStenen());
drawPeddle(g,mijnmodel.getBat());
drawBall(g,mijnmodel.getBall());
}
@Override
public void keyPressed(KeyEvent e){
System.out.println("Key Pressed!!!");
}
//Called when the key is released
@Override
public void keyReleased(KeyEvent e){
System.out.println("Key Released!!!");
}
//Called when a key is typed
@Override
public void keyTyped(KeyEvent e){}
}
问题可能是我正在使用多个类来创建一个窗口(第一个 JFrame,然后是一个包含 2 个 JPanel 的 JPanel,其上是“PlayField”类)并且无法在另一个面板中实现焦点?最好的行动方案是什么?