我一直在尝试帮助我似乎无法按下左箭头键移动我的JLabel。我尝试了很多方法,但仍然没有进展。我究竟做错了什么?我已经将代码设置为按下左键时(无论如何应该)将X变量减少一个将标签向左移动,而是保持原位。
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 :(得分:0)
专注是问题。事件(keyPressed)只有在对象可聚焦且具有焦点时才会被触发。你的JLabel没有焦点,因此不会触发关键事件。
要修复使用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