我试图根据按下的箭头键移动我的照片,但是按键侦听器没有检测到任何按键。我附加了面板的代码,我添加到驱动程序中的框架。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class RacePanel extends JPanel
{
//variables
private ImageIcon backGround = new ImageIcon("images/back.png");
private Penguin p;
private ImageIcon icon1 = new ImageIcon("images/PenguinR.png");
private ImageIcon icon2 = new ImageIcon("images/PenguinL.png");
private int x = 10;
//move left and right methods
public void moveLeft(Penguin x)
{
x.setImageIcon(icon2);
x.setX(x.getX() - 5);
}
public void moveRight(Penguin x)
{
x.setImageIcon(icon1);
x.setX(x.getX() + 5);
}
public RacePanel()
{
JPanel RacePanel = new JPanel();
super.addKeyListener(new Key());
setFocusable(true);
p = new Penguin();
Timer t = new Timer(50, new Listener());
t.start();
}
private class Key implements KeyListener
{
public Key()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
moveRight(p);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
moveLeft(p);
}
if(e.getKeyCode() == KeyEvent.VK_UP)
{
System.out.println("i am listening");
}
repaint();
}
public void keyReleased(KeyEvent e)
{
}
}
//graphics
public void paintComponent(Graphics g)
{
g.drawImage(backGround.getImage(),0,0,800,600,null);
g.drawImage(p.getImageIcon().getImage(),p.getX(),p.getY(),50,100,null);
}
//action listener .05 second loop
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
}
我知道它没有识别按键,因为我添加了一行代码来打印"我正在倾听"如果按下向上箭头并且没有打印任何内容。 我也知道问题不是因为计时器导致我通过将moveRight方法添加到actionPerformed方法来测试它。