簡單我有一個自定義對象播放器,它擴展了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");
}
}
開始由具有看看[如何使用按鍵綁定(https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html ) – MadProgrammer
不要嘗試移動容器周圍的組件。這絕對是一個應該使用自定義繪畫的情況。 –
檢查按下的鍵碼。谷歌「擺動鍵代碼箭頭」導致[本文](https://stackoverflow.com/questions/616924/how-to-check-if-the-key-pressed-was-an-arrow-key-in- java-keylistener) –