-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyMovement
More file actions
78 lines (64 loc) · 1.48 KB
/
Copy pathKeyMovement
File metadata and controls
78 lines (64 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Movement extends Frame implements KeyListener {
int x = 41;
int y = 51;
public Movement() {
addKeyListener(this);// adding key listener for arrow keys
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
setTitle("Basic Arrow Key Movement");
setSize(500, 500);
}
public void paint(Graphics g) {
g.drawString("x=" + x + ", y=" + y, 40, 50);
g.drawRect(40, 50, 400, 400);
g.setColor(Color.cyan);
g.fillRect(x, y, 50, 30);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_UP:
// condition to keep movement inside the box
if (y > 51)
// adjust y coordinate by 1
y -= 5;
break;
case KeyEvent.VK_DOWN:
if (y < 420)
y += 5;
break;
case KeyEvent.VK_LEFT:
if (x > 41)
x -= 5;
break;
case KeyEvent.VK_RIGHT:
if (x < 390)
x += 5;
break;
}
// redraw the screen
repaint();
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
public static void main (String[] args) {
JFrame j = new JFrame();
Movement m = new Movement();
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.pack();
m.setVisible(true);
}
}