HOWTO · Java
JavaFX 顯示文字
本教程演示瞭如何在 JavaFX 中顯示文字。
本頁內容
可以使用 JavaFX.scene.text.Text 類建立和顯示文字。本教程演示如何在 JavaFX 中顯示單行和多行文字。
JavaFX 顯示文字
JavaFX.scene,text.Text 用於在 JavaFX 中建立和顯示文字。可以通過例項化 Text 類來建立文字節點並顯示在場景中。
語法:
Text text = new Text(text);
其中 text 作為引數是文字值。要設定文字的 x 和 y 位置的值,我們使用以下方法:
text.setX(30);
text.setY(30);
上述方法將根據方法中給出的 x 和 y 位置設定文字的位置。按照以下步驟在 JavaFX 中建立和顯示文字:
- 通過擴充套件
Application類並實現start()方法來建立一個類。 - 通過例項化類
Text建立文字。然後使用setX()和setY()方法設定x和y位置。 - 建立一個
組類。 - 建立一個場景物件,例項化
scene類,並將group物件傳遞給scene。 - 通過
setTitle方法為舞臺新增標題,並使用setScene()方法將場景新增到舞臺。 - 使用
show()方法顯示舞臺並啟動應用程式。
讓我們根據上述步驟實現一個示例。
示例程式碼:
package delftstack;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class JavaFX_Display_Text extends Application {
@Override
public void start(Stage Demo_Stage) {
// Create a Text object
Text Demo_Text = new Text();
// Set the text to be added.
Demo_Text.setText("Hello, This is delftstack.com");
// set the position of the text
Demo_Text.setX(80);
Demo_Text.setY(80);
// Create a Group object
Group Group_Root = new Group(Demo_Text);
// Create a scene object
Scene Demo_Scene = new Scene(Group_Root, 600, 300);
// Set title to the Stage
Demo_Stage.setTitle("Text Display");
// Add scene to the stage
Demo_Stage.setScene(Demo_Scene);
// Display the contents of the stage
Demo_Stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
上面的程式碼將在場景中建立並顯示 Text。
輸出:
我們可以使用 Label 而不是 Text 來顯示多行文字。建立一個標籤並將文字傳遞給它。
我們必須將 Text 包裝在 Label 中以將其顯示為多行文字。
示例程式碼:
package delftstack;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFX_Display_Text extends Application {
@Override
public void start(Stage Demo_Stage) {
String Content = "DelftStack is a resource for everyone interested in programming, "
+ "embedded software, and electronics. It covers the programming languages "
+ "like Python, C/C++, C#, and so on in this website's first development stage. "
+ "Open-source hardware also falls in the website's scope, like Arduino, "
+ "Raspberry Pi, and BeagleBone. DelftStack aims to provide tutorials, "
+ "how-to's, and cheat sheets to different levels of developers and hobbyists..";
// Create a Label
Label Demo_Text = new Label(Content);
// wrap the label
Demo_Text.setWrapText(true);
// Set the maximum width of the label
Demo_Text.setMaxWidth(300);
// Set the position of the label
Demo_Text.setTranslateX(30);
Demo_Text.setTranslateY(30);
Group Text_Root = new Group();
Text_Root.getChildren().add(Demo_Text);
// Set the stage
Scene Text_Scene = new Scene(Text_Root, 595, 150, Color.BEIGE);
Demo_Stage.setTitle("Display Multiline Text");
Demo_Stage.setScene(Text_Scene);
Demo_Stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
上面的程式碼會將標籤中包含的文字顯示為多行。
輸出: