Java GUI:如何使用箭头键移动对象?

时间:2019-06-24 21:19:44

标签: java swing user-interface jframe

我是Java编程的新手,我正在尝试使用KeyListener使用箭头键移动对象,但该对象不会移动。我已经用谷歌搜索了,但是我似乎无法弄清楚我要去哪里。我能够自己移动对象,但是将速度设置为0并添加keyListener之后,什么也没发生。请检查我的代码并帮助我找出我做错了什么。

import java.awt.*;
import javax.swing.*;
import java.io.*;



   public class Games extends JFrame{
    public Games(){
    super.setTitle("Sokoban");
    super.setSize(600, 600);
    super.setLocation(400, 300);
    super.setResizable(false);

    super.add(new Contents());
    super.setVisible(true);
    super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    super.setLayout(new BorderLayout());




}


public static void main(String[] args)  {
    new Games();





}


    }import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;

public class Contents extends JPanel implements ActionListener, KeyListener {
    private Image person;
    private int x=0, y= 0;
    private int speedXCordinate= 0, speedYCordinate= 0;

Timer time  = new Timer(7, this);



public Contents(){
    super.setDoubleBuffered(true);

    time.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);



}

@Override
public void paintComponent(Graphics g){
    ImageIcon p = new ImageIcon(this.getClass().getResource("person.jpeg"));
    Graphics2D q = (Graphics2D) g;


    person = p.getImage();
    q.drawImage(person, x, y, this);






}



@Override
public void actionPerformed(ActionEvent e) {

   repaint();
   x+= speedXCordinate;
   y+=speedYCordinate;




}

public void up(){
    speedXCordinate=0;
    speedYCordinate=-1;
}
public void down(){
    speedXCordinate=0;
    speedYCordinate=1;
}
public void left(){
    speedXCordinate=-1;
    speedYCordinate=0;
}
public void right(){
    speedYCordinate=1;
    speedYCordinate=0;
}

@Override
public void keyTyped(KeyEvent e) { . //method for moving object
    int c= e.getKeyCode();
    if( c == KeyEvent.VK_LEFT){
       left();
    }
    if(c==KeyEvent.VK_RIGHT){
        right();
    }
    if(c==KeyEvent.VK_UP){
        up();

    }
    if(c==KeyEvent.VK_DOWN){
       down();


    }


}

@Override
public void keyPressed(KeyEvent e) {

}

@Override
public void keyReleased(KeyEvent e) {
    speedXCordinate=0;
    speedYCordinate=0;

}

}

1 个答案:

答案 0 :(得分:-2)

在设置X和Y速度之间似乎需要延迟,可以在设置速度并将其更改回0之间使用Thread.sleep(milliseconds)