Skip to content

Commit f037a2f

Browse files
committed
commit Exercise_30_06
1 parent 7076167 commit f037a2f

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package exercise_30_06;
2+
3+
import javafx.application.Platform;
4+
import javafx.scene.layout.Pane;
5+
import javafx.scene.paint.Color;
6+
import javafx.scene.shape.Circle;
7+
8+
public class BallPane extends Pane {
9+
public final double radius = 20;
10+
private double x = radius, y = radius;
11+
private double dx = 1, dy = 1;
12+
private Circle circle = new Circle(x, y, radius);
13+
private int sleepTime = 10;
14+
private Thread thread = new Thread(() -> {
15+
try {
16+
while(true) {
17+
Platform.runLater(() -> moveBall());
18+
Thread.sleep(sleepTime);
19+
}
20+
}
21+
catch (InterruptedException ex) {
22+
}
23+
});
24+
25+
public BallPane() {
26+
circle.setFill(Color.GREEN);
27+
getChildren().add(circle);
28+
thread.start();
29+
}
30+
31+
public void resume() {
32+
thread.resume();
33+
}
34+
35+
public void suspend() {
36+
thread.suspend();
37+
}
38+
39+
public void increaseSpeed() {
40+
if(sleepTime > 1) {
41+
sleepTime--;
42+
}
43+
}
44+
45+
public void decreaseSpeed() {
46+
sleepTime++;
47+
}
48+
49+
protected void moveBall() {
50+
if(x < radius || x > getWidth() - radius) {
51+
dx *= -1;
52+
}
53+
if(y < radius || y > getHeight() - radius) {
54+
dy *= -1;
55+
}
56+
57+
x += dx;
58+
y += dy;
59+
circle.setCenterX(x);
60+
circle.setCenterY(y);
61+
}
62+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package exercise_30_06;
2+
3+
import javafx.application.Application;
4+
import javafx.scene.Scene;
5+
import javafx.scene.input.KeyCode;
6+
import javafx.stage.Stage;
7+
8+
public class Exercise_30_06 extends Application {
9+
10+
@Override
11+
public void start(Stage primaryStage) {
12+
BallPane ballPane = new BallPane();
13+
14+
ballPane.setOnMousePressed(e -> ballPane.suspend());
15+
ballPane.setOnMouseReleased(e -> ballPane.resume());
16+
17+
ballPane.setOnKeyPressed(e -> {
18+
if (e.getCode() == KeyCode.UP) {
19+
ballPane.increaseSpeed();
20+
}
21+
else if (e.getCode() == KeyCode.DOWN) {
22+
ballPane.decreaseSpeed();
23+
}
24+
});
25+
26+
Scene scene = new Scene(ballPane, 250, 150);
27+
primaryStage.setTitle("Exercise_30_06");
28+
primaryStage.setScene(scene);
29+
primaryStage.show();
30+
31+
ballPane.requestFocus();
32+
}
33+
34+
public static void main(String[] args) {
35+
launch(args);
36+
}
37+
}

0 commit comments

Comments
 (0)