JavaFX - 標籤



標籤是一段文字,用於描述或告知使用者應用程式中其他元素的功能。它有助於減少混淆並提供清晰度,從而帶來更好的使用者體驗。請記住,它不是一個可編輯的文字控制元件。在下圖中,我們可以看到一個紅色框中的按鈕,以及一些描述其用途的文字:

JavaFX Label

JavaFX 中的標籤

在 JavaFX 中,標籤由名為Label的類表示,該類屬於javafx.scene.control包。要在 JavaFX 應用程式中建立標籤,可以使用以下任何建構函式:

  • Label() - 這是預設建構函式,它構造一個空標籤。

  • Label(String str) - 它使用預定義文字構造一個標籤。

  • Label(String str, Node graph) - 它使用指定的文字和圖形構造一個新的標籤。

在 JavaFX 中建立標籤的步驟

要在 JavaFX 中建立標籤,請按照以下步驟操作:

步驟 1:例項化 Label 類

如前所述,我們需要例項化Label類來建立標籤文字。我們可以使用其預設建構函式或引數化建構函式。如果我們使用預設建構函式,則可以使用setText()方法新增標籤文字。

// Instanting the Label class
Label label = new Label("Sample label");

步驟 2:設定標籤的所需屬性

就像文字節點一樣,我們可以分別使用setFont()方法和setFill()方法來設定 JavaFX 中標籤節點的字型和字型顏色等所需屬性。

// 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);

步驟 4:啟動應用程式

建立標籤並設定其屬性後,定義一個group物件來儲存標籤。接下來,透過將 group 物件和場景的尺寸傳遞給其建構函式來建立一個Scene物件。然後,設定舞臺並啟動應用程式以顯示結果。

示例

在下面的示例中,我們將建立一個 JavaFX 應用程式中的標籤。將此程式碼儲存在名為JavafxLabel.java的檔案中。

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 JavafxLabel 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, 400, 300, Color.BEIGE);
      stage.setTitle("Label Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

要從命令提示符編譯和執行儲存的 Java 檔案,請使用以下命令:

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxLabel.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxLabel

輸出

當我們執行上述程式碼時,它將生成如下所示的標籤文字。

Javafx Label Output
廣告