how to make an object move with arrow keys in java

Solutions on MaxInterview for how to make an object move with arrow keys in java by the best coders in the world

showing results for - "how to make an object move with arrow keys in java"
Wiley
31 Jan 2020
1import java.awt.Canvas;
2import java.awt.Dimension;
3import java.awt.Graphics2D;
4import java.awt.image.BufferStrategy;
5import java.awt.event.*;
6import javax.swing.*;
7 
8public class HandlingEvents implements Runnable {
9 
10    JFrame frame;
11    int myX = 400;
12    int myY = 400;
13    Canvas canvas;
14    BufferStrategy bufferStrategy;
15    boolean running = true;
16 
17    public HandlingEvents() {
18        frame = new JFrame("Basic Game");
19        JPanel panel = (JPanel) frame.getContentPane();
20        panel.setPreferredSize(new Dimension(500, 500));
21        panel.setLayout(null);
22        canvas = new Canvas();
23        canvas.setBounds(0, 0, 500, 500);
24        canvas.setIgnoreRepaint(true);
25        panel.add(canvas);
26        canvas.addKeyListener(new KeyAdapter() {
27            @Override
28            public void keyPressed(KeyEvent evt) {
29                moveIt(evt);
30            }
31        });
32        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
33        frame.pack();
34        frame.setResizable(false);
35        frame.setVisible(true);
36        canvas.createBufferStrategy(2);
37        bufferStrategy = canvas.getBufferStrategy();
38        canvas.requestFocus();
39    }
40    public void run() {
41        while (running = true) {
42            Paint();
43            try {
44                Thread.sleep(25);
45            } catch (InterruptedException e) {
46            }
47        }
48    }
49    public static void main(String[] args) {
50        HandlingEvents ex = new HandlingEvents();
51        new Thread(ex).start();
52    }
53    public void Paint() {
54        Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
55        g.clearRect(0, 0, 500, 500);
56        Paint(g);
57        bufferStrategy.show();
58    }
59 
60    protected void Paint(Graphics2D g) {
61        g.fillOval(myX, myY, 30, 30);
62    }
63    public void moveIt(KeyEvent evt) {
64     switch (evt.getKeyCode()) {
65            case KeyEvent.VK_DOWN:
66                myY += 5;
67                break;
68            case KeyEvent.VK_UP:
69                myY -= 5;
70                break;
71            case KeyEvent.VK_LEFT:
72                myX -= 5;
73                break;
74            case KeyEvent.VK_RIGHT:
75                myX += 5;
76                break;
77        }
78         
79       
80         
81    }
82}
83