如何正确添加keylistener

时间:2015-05-19 15:02:19

标签: java swing compiler-errors

我想把keylistener放到左边和右边移动“download.jpg”。我把;但错误说明了;需要。我做错了什么?我需要修理什么?我需要添加任何内容吗?

    public class GameScreen extends JPanel implements KeyListener    {

        public  BufferedImage bg;
        public  BufferedImage ci;
        public JLabel lab;
        int ciXp = 250;
        int ciYp = 665;
        int ciWidth = 330;
        int ciHeight = 745;

    public GameScreen()
    {
        gui();

    }

    public void gui()
    {
    try{
         bg = ImageIO.read(new File("supermario.jpg"));
         ci = ImageIO.read(new File("download.png"));
        }
        catch(Exception ex){
            }



    }


    public void paintComponent(Graphics g)
    {
        g.drawImage(bg,0,0,null);
        g.drawImage(ci,ciXp,ciYp,ciWidth,ciHeight,0,0,ci.getWidth(),ci.getHeight(),null);
    }

    public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
       int ciXp-10;
    }
    if (key == KeyEvent.VK_RIGHT) {
       int ciXp+10;
    }
}
}

1 个答案:

答案 0 :(得分:0)

gui()方法中添加以下行

addKeyListener(this);