File tree Expand file tree Collapse file tree 2 files changed +99
-0
lines changed
Chapter_30/exercise_30_06 Expand file tree Collapse file tree 2 files changed +99
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments