Java Reference
In-Depth Information
5 import javafx.scene.layout.StackPane;
6 import javafx.scene.layout.HBox;
7 import javafx.scene.layout.BorderPane;
8 import javafx.scene.paint.Color;
9 import javafx.scene.shape.Circle;
10 import javafx.stage.Stage;
11
12 public class ControlCircleWithoutEventHandling extends Application {
13 @Override // Override the start method in the Application class
14 public void start(Stage primaryStage) {
15 StackPane pane = new StackPane();
16 Circle circle = new Circle( 50 );
17 circle.setStroke(Color.BLACK);
18 circle.setFill(Color.WHITE);
19 pane.getChildren().add(circle);
20
21 HBox hBox = new HBox();
22 hBox.setSpacing( 10 );
23 hBox.setAlignment(Pos.CENTER);
24 Button btEnlarge = new Button( "Enlarge" );
25 Button btShrink = new Button( "Shrink" );
26 hBox.getChildren().add(btEnlarge);
27 hBox.getChildren().add(btShrink);
28
29 BorderPane borderPane = new BorderPane();
30 borderPane.setCenter(pane);
31 borderPane.setBottom(hBox);
32 BorderPane.setAlignment(hBox, Pos.CENTER);
33
34 // Create a scene and place it in the stage
35 Scene scene = new Scene(borderPane, 200 , 150 );
36 primaryStage.setTitle( "ControlCircle" ); // Set the stage title
37 primaryStage.setScene(scene); // Place the scene in the stage
38 primaryStage.show(); // Display the stage
39 }
49 }
circle
buttons
How do you use the buttons to enlarge or shrink the circle? When the Enlarge button is clicked,
you want the circle to be repainted with a larger radius. How can you accomplish this? You can
expand and modify the program in ListingĀ 15.2 into ListingĀ 15.3 with the following features:
second version
1. Define a new class named CirclePane for displaying the circle in a pane (lines 51-68).
This new class displays a circle and provides the enlarge and shrink methods for
increasing and decreasing the radius of the circle (lines 60-62, 64-67). It is a good
strategy to design a class to model a circle pane with supporting methods so that these
related methods along with the circle are coupled in one object.
2. Create a CirclePane object and declare circlePane as a data field to reference this
object (line 15) in the ControlCircle class. The methods in the ControlCircle
class can now access the CirclePane object through this data field.
3. Define a handler class named EnlargeHandler that implements
EventHandler<ActionEvent> (lines 43-48). To make the reference variable
circlePane accessible from the handle method, define EnlargeHandler as an
inner class of the ControlCircle class. ( Inner classes are defined inside another
class. We use an inner class here and will introduce it fully in the next section.)
inner class
4. Register the handler for the Enlarge button (line 29) and implement the handle method
in EnlargeHandler to invoke circlePane.enlarge() (line 46).
 
Search WWH ::




Custom Search