如何使用键盘控制移动对象?

时间:2016-10-21 15:26:21

标签: java swing awt

好吧,所以我创建了一些非常基本的代码。我知道如何移动物体,但我想知道如何使用键盘移动物体。例如,W表示正向,A表示向左,S表示向后,D表示向右。

以下是代码:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Game extends JPanel {

    int x = 0;
    int y = 0;

    /*private void moveBall() {  // This patch is where the movement was before
        x = x + 1;
        y = y + 1;
    } */
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.fillOval(x, y, 30, 30); // This is the object to move w/ keyboard
    }

    public static void main(String [] args) throws InterruptedException {
        JFrame frame = new JFrame("Frame");
        Game game = new Game();
        frame.add(game);
        frame.setSize(500, 420);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        while(true) {
            game.repaint();
            Thread.sleep(10);
        }
    }
}

0 个答案:

没有答案