简单我有一个自定义对象播放器,它扩展了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) –