-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveTheCircle2.java
More file actions
127 lines (105 loc) · 2.36 KB
/
Copy pathMoveTheCircle2.java
File metadata and controls
127 lines (105 loc) · 2.36 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JPanel;
import java.awt.event.KeyListener;
import java.applet.*;
//program description: moves a circle around a scren
//arrow keys to moves around screen, space bar to stop moving
public class MoveTheCircle2{
/**
*
*/
private static final long serialVersionUID = 1L;
public MoveTheCircle2 () {
JFrame f = new JFrame ();
f.setSize(500, 500);
f.setResizable (false);
f.add (new DrawCircle());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public class DrawCircle extends JPanel implements KeyListener, ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
int x = 100;
int y = 100;
int dx = 0;
int dy = 0;
Timer t = new Timer (1, this);
public DrawCircle (){
t.start ();
setBackground(Color.BLACK);
setFocusTraversalKeysEnabled(false);
addKeyListener(this);
setFocusable (true);
}
public void paintComponent (Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillOval(x, y, 50, 50);
}
public void actionPerformed(ActionEvent e) {
if (x + dx <= 0){
x = 500;
}
if (x + dx >= 500){
x = 0;
}
if (y + dy <= 0){
y = 478;
}
if (y + dy >= 478){
y = 0;
}
x +=dx;
y +=dy;
repaint();
}
//set movement
public void keyPressed(KeyEvent e) {
int event = e.getKeyCode();
if (event == KeyEvent.VK_RIGHT){
dx = 1;
dy = 0;
}
if (event == KeyEvent.VK_LEFT){
dx = -1;
dy = 0;
}
if (event == KeyEvent.VK_DOWN){
dx = 0;
dy = 1;
}
if (event == KeyEvent.VK_UP){
dx = 0;
dy = -1;
}
if (event == KeyEvent.VK_SPACE){
dx = 0;
dy = 0;
}
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
public static void main(String[] args) {
new MoveTheCircle2 ();
}
}