2017-05-31 76 views
-2

简单我有一个自定义对象播放器,它扩展了JLabel,我想向我的对象添加一个侦听器,允许我使用箭头键更改位置。 Swing也有一个时间表更新方法,否则当我预见密钥问题不会继续响应,因为我持有密钥。下面如何使用箭头键将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"); 
    } 
} 
+0

开始由具有看看[如何使用按键绑定(https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html ) – MadProgrammer

+2

不要尝试移动容器周围的组件。这绝对是一个应该使用自定义绘画的情况。 –

+0

检查按下的键码。谷歌“摆动键代码箭头”导致[本文](https://stackoverflow.com/questions/616924/how-to-check-if-the-key-pressed-was-an-arrow-key-in- java-keylistener) –

回答

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) { 

      } 
     }); 
+0

我查看了每个人发给我的链接,这样就清除了我的一些混乱,但我的对象仍然没有用我的键盘按键响应,我拿走了你建议的代码。代替“char”我把'w'放在我的钥匙上,我用了VK_W。关于执行的操作方法,我实现它像Player.this.setLocation(100,200); – Cosmik11

+1

LayoutManager不关心运行时的变化,需要在actionPerformed内部调用revalidate和repaint(一次作为最后一个代码,完成对已经可见的Swing GUI的所有更改后) – mKorbel

+0

您的密钥按键是否已获得注册?重点好吗? –

相关问题