0

Alright, so I created some very basic code. I know how I can make an object move, but I want to know how I can make the object move with the keyboard. For example, W for forward, A for left, S for backward, and D for right.

Here's the code:

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);
        }
    }
}
sanastasiadis
  • 1,182
  • 1
  • 15
  • 23
  • Have you looked into [key listeners](https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html)? – Ash Oct 21 '16 at 15:33
  • I looked into it and it led me to what I think is my answer – christien425 Oct 21 '16 at 15:41
  • Still stuck or happy to carry on with those examples? – Ash Oct 21 '16 at 15:45
  • 1
    I'm good with the examples – christien425 Oct 21 '16 at 15:46
  • cool, hope the project goes well – Ash Oct 21 '16 at 15:49
  • Study more of the similar questions, and you'll see: don't use KeyListeners as they're dodgy, especially with regard to component focus -- if the listened-to component loses focus, the KeyListener no longer works. Instead (as most of the decent answers will tell you) use [Key Bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html). – Hovercraft Full Of Eels Oct 21 '16 at 16:07
  • Also check out [these links on Key Bindings vs. KeyListeners](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+key+binding+vs+keylistener) – Hovercraft Full Of Eels Oct 21 '16 at 16:09

0 Answers0