JavaFX的属性经常通过绑定来综合。这是一种表达变量间关系的机制。可以将一个目标对象和一个源对象绑定,如果源对象中的值改变了,则目标对象也将自动改变。目标对象称为绑定对象或绑定属性,源对象称为可绑定对象或可观察对象。下。下列程序是对《Java 程序语言设计》其中一道习题的实现(原答案并不完整):
1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.layout.Pane; 4 import javafx.scene.paint.Color; 5 import javafx.scene.shape.Line; 6 import javafx.scene.shape.Rectangle; 7 import javafx.stage.Stage; 8 9 public class java1414 extends Application {10 @Override // Override the start method in the Application class11 public void start(Stage primaryStage) {12 Pane pane = new Pane();13 double paneWidth = 200;14 double paneHeight = 200;15 16 // Draw the front rectangle17 Rectangle r1 = new Rectangle();18 r1.xProperty().bind(pane.widthProperty().multiply(0.05));19 r1.yProperty().bind(pane.heightProperty().multiply(0.30));20 r1.widthProperty().bind(pane.widthProperty().multiply(0.75));21 r1.heightProperty().bind(pane.heightProperty().multiply(0.60));22 r1.setFill(new Color(1, 1, 1, 0));23 r1.setStroke(Color.BLACK);24 25 // Draw the back rectangle26 Rectangle r2 = new Rectangle();27 r2.xProperty().bind(pane.widthProperty().multiply(0.15));28 r2.yProperty().bind(pane.heightProperty().multiply(0.06));29 r2.widthProperty().bind(pane.widthProperty().multiply(0.75));30 r2.heightProperty().bind(pane.heightProperty().multiply(0.60));31 r2.setFill(new Color(1, 1, 1, 0));32 r2.setStroke(Color.BLACK);33 34 // Connect the corners35 Line line1 = new Line();36 line1.startXProperty().bind(pane.widthProperty().multiply(0.05));37 line1.startYProperty().bind(pane.heightProperty().multiply(0.30));38 line1.endXProperty().bind(pane.widthProperty().multiply(0.15));39 line1.endYProperty().bind(pane.heightProperty().multiply(0.06));40 Line line2 = new Line();41 line2.startXProperty().bind(pane.widthProperty().multiply(0.05));42 line2.startYProperty().bind(pane.heightProperty().multiply(0.90));43 line2.endXProperty().bind(pane.widthProperty().multiply(0.15));44 line2.endYProperty().bind(pane.heightProperty().multiply(0.66));45 Line line3 = new Line();46 line3.startXProperty().bind(pane.widthProperty().multiply(0.80));47 line3.startYProperty().bind(pane.heightProperty().multiply(0.30));48 line3.endXProperty().bind(pane.widthProperty().multiply(0.90));49 line3.endYProperty().bind(pane.heightProperty().multiply(0.06));50 Line line4 = new Line();51 line4.startXProperty().bind(pane.widthProperty().multiply(0.80));52 line4.startYProperty().bind(pane.heightProperty().multiply(0.90));53 line4.endXProperty().bind(pane.widthProperty().multiply(0.90));54 line4.endYProperty().bind(pane.heightProperty().multiply(0.66));55 56 pane.getChildren().addAll(r1, r2, line1, line2, line3, line4);57 58 // Create a scene and place it in the stage59 Scene scene = new Scene(pane, paneWidth, paneHeight);60 primaryStage.setTitle("Exercise14_14"); // Set the stage title61 primaryStage.setScene(scene); // Place the scene in the stage62 primaryStage.show(); // Display the stage63 }64 }