例子
以下是演示 JavaFX 中旋转变换的程序。在这里,我们在同一位置创建 2 个矩形节点,具有相同的尺寸但具有不同的颜色(Blurywood 和 Blue)。我们还在具有 Blurywood 颜色的矩形上应用旋转变换。
将此代码保存在名称为的文件中 RotationExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class RotationExample extends Application {
@Override
public void start(Stage stage) {
//Drawing Rectangle1
Rectangle rectangle1 = new Rectangle(150, 75, 200, 150);
rectangle1.setFill(Color.BLUE);
rectangle1.setStroke(Color.BLACK);
//Drawing Rectangle2
Rectangle rectangle2 = new Rectangle(150, 75, 200, 150);
//Setting the color of the rectangle
rectangle2.setFill(Color.BURLYWOOD);
//Setting the stroke color of the rectangle
rectangle2.setStroke(Color.BLACK);
//creating the rotation transformation
Rotate rotate = new Rotate();
//Setting the angle for the rotation
rotate.setAngle(20);
//Setting pivot points for the rotation
rotate.setPivotX(150);
rotate.setPivotY(225);
//Adding the transformation to rectangle2
rectangle2.getTransforms().addAll(rotate);
//Creating a Group object
Group root = new Group(rectangle1, rectangle2);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Rotation transformation example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令从命令提示符编译并执行保存的 java 文件。
javac RotationExample.java
java RotationExample
在执行时,上面的程序会生成一个 javaFx 窗口,如下所示。