我一直試圖幫助,我似乎無法移動我的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
}*/
}}
你試過'label.setBounds( - X,Y,24,24)'? –
問題是重點 – DarkV1