java用左键移动JLabel?
我一直在尝试,即使有人帮助,我似乎也无法按左箭头键移动我的JLabel。我尝试了许多方法,但仍然没有取得任何进展。我做错了什么?我已经将代码设置为当按下left键时(无论如何都应该是这样),将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
}*/
}}
# 1 楼答案
重点是问题所在。As事件(按键)仅在对象可聚焦且具有焦点时才会激发。您的JLabel没有焦点,因此不会触发keyevents
要修复此问题,请使用Key BindingsAPI
这里有一个例子
然后打电话给
设置新的x-y值后更新Jlabel
这里有一个完美的链接,可以看到焦点如何影响你的按键在swing中的工作
http://www.javaworld.com/article/2076720/core-java/focus-on-swing.html