如何使用 JavaFX 建立標籤?


使用 Label 元件,可在使用者介面上顯示文字元素/影像。這是一個不可編輯的文字控制元件,主要用於指定應用程式中其他節點的目的。

在 JavaFX 中,可透過例項化 javafx.scene.control.Label 類來建立標籤。

就像文字節點一樣,可以使用 setFont() 方法為 JavaFX 中的文字節點設定所需的字型,還可以使用 setFill() 方法為其新增顏色。

要建立標籤 -

  • 例項化 Label 類。

  • 為其設定所需屬性。

  • 將標籤新增到場景。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class LabelExample extends Application {
   public void start(Stage stage) {
      //Creating a Label
      Label label = new Label("Sample label");
      //Setting font to the label
      Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 25);
      label.setFont(font);
      //Filling color to the label
      label.setTextFill(Color.BROWN);
      //Setting the position
      label.setTranslateX(150);
      label.setTranslateY(25);
      Group root = new Group();
      root.getChildren().add(label);
      //Setting the stage
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Label Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新時間: 2020 年 5 月 16 日

3K+ 瀏覽量

開啟您的 職業發展

完成課程可獲得認證

開始
廣告