使用KeyAdapter输入键盘

时间:2014-03-16 18:51:15

标签: java swing animation paintcomponent keylistener

我试图在java中制作一个简单的游戏,你可以在4个方向上移动玩家(Defender)。我尝试用钥匙适配器进行钥匙检测,但它不起作用。可能是什么问题(我试图在按键时执行System.out.println以确保问题不在防御者处)? 代码:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class DefenderComponent extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;

    private static final int WIDTH = 160;
    private static final int HEIGHT = 120;
    private static final int SCALE = 4;

    Defender player = new Defender();

    public DefenderComponent() {
        Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
        setMinimumSize(size);
        setMaximumSize(size);
        setPreferredSize(size);

        addKeyListener(new TKeyListener());

        Timer timer = new Timer(5, this);
                timer.start();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test2");
        frame.add(new DefenderComponent());
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        frame.setFocusable(true);

        new DefenderComponent();
    }


    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        Image i = player.getImage();
        g2d.drawImage(i, player.getX(), player.getY(), i.getWidth(this) * SCALE, i.getHeight(this) * SCALE, this);
    }

    public void actionPerformed(ActionEvent e) {
        player.move();
        repaint();  
    }
}

2 个答案:

答案 0 :(得分:0)

frame.addActionListener(this);

是你错过的。

那条线说。这个类是一个ActionListener。请在收到诉讼时致电本课程。

如果要将ActionListener添加到JPanel

public DefenderComponent() {
    addActionListener(this);
    ....
}

答案 1 :(得分:0)

仅为具有焦点的组件生成KeyEvents。默认情况下,JPanel不可聚焦。

不要使用KeyListener。相反,你应该使用更灵活的键绑定。

有关更多信息和示例,请参阅Motion Using the Keyboard