2016-05-09 83 views
1

我一直試圖幫助,我似乎無法移動我的JLabel周圍按左箭頭鍵。我嘗試過很多方法,但仍然沒有進展。我究竟做錯了什麼?當按下左鍵時(反正它應該是這樣),我將代碼設置爲減少一個標籤向左移動的X變量,而代之以保持原位。用左鍵移動JLabel?

package com.game.user; 

import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.border.EmptyBorder; 

public class Main { 
    static int x = 474; 
    static int y = 202; 
    public static void main(String[] args) { 
     JFrame frame = new JFrame("game"); 
     frame.setVisible(true); 
     frame.setBounds(700, 700, 700, 700); 
     frame.setLayout(null); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JLabel label = new JLabel(); 
     label.setIcon(new ImageIcon("E:\\sword.png")); 
     label.setBounds(x, y, 24, 24); 
     label.setVisible(true); 
     JPanel contentPane = new JPanel(); 
     frame.setContentPane(contentPane); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     contentPane.setLayout(null); 
     contentPane.add(label); 
    /* Keyboard key = new Keyboard(); 
      addKeyListener(key); 
     */label.addKeyListener(new KeyAdapter() { 
      @Override 
      public void keyPressed(KeyEvent e) { 
      if(e.getKeyChar()==KeyEvent.VK_LEFT){ 
       x--; 
      } 



      } 
      }); 

      /*String keyString; 
     if (id == KeyEvent.KEY_TYPED) { 
      char c = e.getKeyChar(); 
      keyString = "key character = '" + c + "'"; 
      System.out.print("hello"); 
     } else { 
      int keyCode = e.getKeyCode(); 
      keyString = "key code = " + keyCode+ " ("+ KeyEvent.getKeyText(keyCode)+ ")"; 
     } 
      } 
     }); 

    } 

    private static void addKeyListener(Keyboard key) { 
     // TODO Auto-generated method stub 

    }*/ 

    }} 
+0

你試過'label.setBounds( - X,Y,24,24)'? –

+0

問題是重點 – DarkV1

回答

0

重點是問題所在。由於事件(keyPressed)只會在對象可以聚焦且具有焦點的情況下觸發。你的JLabel沒有焦點,因此keyevents不會被解僱。

要解決使用Key Bindings API

下面是一個例子。

this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "right"); 
this.getActionMap().put("right", new AbstractAction() { 
    public void actionPerformed(ActionEvent e) { 
     //increment X as it is moving Right 
    } 
}); 

然後調用...

lbl.revalidate(); 

到新的x-y的值已設置之後更新的JLabel。

這裏是完美的鏈接查看重點是如何影響你的按鍵放在揮杆是如何工作的

http://www.javaworld.com/article/2076720/core-java/focus-on-swing.html

+0

@Andymc希望這可以幫助 – DarkV1