HOWTO · Java
JavaFX 文字旋轉
本教程演示瞭如何在 JavaFX 中旋轉文字。
本頁內容
可以使用 JavaFX.scene.text.Text 類建立文字節點,並在 JavaFX 中使用 setRotate() 來旋轉文字。本教程演示瞭如何在 JavaFX 中旋轉文字。
JavaFX 文字旋轉
JavaFX 中使用 setRotate() 方法來旋轉文字。文字節點放置在場景中,並將圍繞 x 和 y 位置旋轉。
在例項化 Text 類時,這些 x 和 y 位置被傳遞到文字中。
語法:
text.setRotate(int);
上述語法中的 int 是文字的旋轉值。以下是在 JavaFX 中旋轉文字的步驟。
-
建立一個擴充套件
Application類的類。 -
在
start方法中將標題設定為舞臺。 -
通過例項化
Group類來建立一個組。 -
通過例項化
Scene類並將Group傳遞給它來建立場景。 -
用給定的值初始化
x、y和RGB。 -
通過例項化
Text類並傳遞x、y和text值來建立文字。 -
通過
SetFill()方法為文字填充顏色。 -
使用
setRotate()方法設定旋轉度數。 -
將
文字新增到組。 -
將場景傳遞到舞臺並通過
Show方法顯示舞臺並在 main 方法中啟動應用程式。
讓我們嘗試根據上述步驟實現一個示例。
完整原始碼:
package delftstack;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class JavaFX_TextRotate extends Application {
@Override
public void start(Stage Demo_Stage) {
Demo_Stage.setTitle("Text");
Group Group_Root = new Group();
Scene Demo_Scene = new Scene(Group_Root, 300, 250, Color.WHITE);
int x = 150;
int y = 150;
int RED = 30;
int GREEN = 40;
int BLUE = 50;
Text Demo_Text = new Text(x, y, "Delftstack");
Demo_Text.setFill(Color.rgb(RED, GREEN, BLUE, .99));
Demo_Text.setRotate(45);
Group_Root.getChildren().add(Demo_Text);
Demo_Stage.setScene(Demo_Scene);
Demo_Stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
上面的程式碼會將文字旋轉 45 度。
輸出:
這是另一個基於隨機 x 和 y 位置和隨機旋轉度數旋轉多個文字的示例。
示例程式碼:
package delftstack;
import java.util.Random;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class JavaFX_Rotate extends Application {
@Override
public void start(Stage Demo_Stage) {
Demo_Stage.setTitle("TEXT");
Group Group_Root = new Group();
Scene Demo_Scene = new Scene(Group_Root, 300, 250, Color.WHITE);
Random Random_Number = new Random(System.currentTimeMillis());
for (int i = 0; i < 100; i++) {
int x = Random_Number.nextInt((int) Demo_Scene.getWidth());
int y = Random_Number.nextInt((int) Demo_Scene.getHeight());
int RED = Random_Number.nextInt(255);
int GREEN = Random_Number.nextInt(255);
int BLUE = Random_Number.nextInt(255);
Text Demo_Text = new Text(x, y, "Delftstack");
int Rotation = Random_Number.nextInt(180);
Demo_Text.setFill(Color.rgb(RED, GREEN, BLUE, .99));
Demo_Text.setRotate(Rotation);
Group_Root.getChildren().add(Demo_Text);
}
Demo_Stage.setScene(Demo_Scene);
Demo_Stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
上面的程式碼將使用隨機的 x、y、RGB 和旋轉度數旋轉多個文字。
輸出: