如何使用箭头键在Swing中移动JLabel

时间:2017-05-31 06:23:31

标签: java swing jlabel keylistener

要简洁我有一个扩展JLabel的自定义对象播放器,我想在我的对象中添加一个监听器,允许我用箭头键改变位置。 Swing还有一个时间表更新方法,否则当我预见到密钥的问题不能继续响应,因为我持有密钥。

public class Player extends JLabel implements Stats{
    private int hp;
    private int bulletcount;
    public Player(int hitpoints, int clip) throws IOException{
        hp=hitpoints;
        bulletcount=clip;
        ImageIcon ship= new ImageIcon("Images/fighterjet.png");
        this.setIcon(ship);
        movement mk= new movement();
        this.addKeyListener(mk);
    }
下面的

是我的听众类

public class movement implements KeyListener {
    boolean pressed;


    @Override
    public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
        if(e.getKeyCode()  == KeyEvent.VK_CAPS_LOCK)
            e.getComponent().setBounds(1000, 1000, 60, 10000);
            pressed=true;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }
下面是

我的司机

public class Main extends JFrame{

    public static void main(String[] args) throws IOException {
        Main window =new Main();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(500,500);

        Player uno= new Player(10,50);

        window.add(uno);
        window.setVisible(true);
        window.setTitle("SPACE");
    }
}

1 个答案:

答案 0 :(得分:0)

如前所述,您应该使用键绑定来处理键盘事件。

现在你的JLabel变成了:

public class Player extends JLabel implements Stats{
private int hp;
private int bulletcount;

public Player(int hitpoints, int clip) throws IOException{
    hp=hitpoints;
    bulletcount=clip;
    ImageIcon ship= new ImageIcon("Images/fighterjet.png");
    this.setIcon(ship);
    movement mk= new movement();

getInputMap().put(KeyStroke.getKeyStroke((char) java.awt.event.KeyEvent.VK_CAPS_LOCK), "doSomething");
        getActionMap().put("doSomething", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });