在 Java 中用 JavaFx 庫標註文字顏色

MD Aminul Islam 2024年2月15日
  1. 在 Java 中使用 setStyle() 方法為文字標籤著色
  2. 改變標籤文字顏色的其他方法
在 Java 中用 JavaFx 庫標註文字顏色

有時我們需要對文字進行著色以使它們專注於使用者。在 JavaFX 中,我們可以通過包含 setStyle() 方法非常輕鬆地做到這一點。

在本文中,我們將瞭解如何更改標籤的文字顏色,並且我們還將看到一個必要的示例和適當的解釋,以便更容易理解該主題。

在 Java 中使用 setStyle() 方法為文字標籤著色

在下面的示例中,我們只是將要閱讀的文字顏色和背景顏色設定為黃色。首先,我們匯入以下使其工作所需的 JavaFx 庫。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

完整原始碼:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class FXlabel extends Application {
  public void start(Stage PrimaryStage) throws Exception {
    PrimaryStage.setTitle("Label Color"); // Setting the application title

    Label lbl = new Label("This is the colored text !!!"); // Creating a simple label with a text
                                                           // "This is the colored text !!!"
    lbl.setStyle(
        "-fx-text-fill: red; -fx-background-color: yellow"); // Styling the text by applying
                                                             // necessary CSS properties.
    Scene scene = new Scene(lbl, 200, 100); // Creating a scene
    PrimaryStage.setScene(scene); // Setting the scene to stage
    PrimaryStage.show(); // Make the stage visible
  }

  public static void main(String[] args) {
    Application.launch(args); // Launching the application
  }
}

lbl.setStyle("-fx-text-fill: red; -fx-background-color: yellow"); 行中,我們使用 setStyle() 方法將一些額外的 CSS 屬性應用於標籤。詳細地說,我們在這裡使用的第一個屬性是 -fx-text-fill: red; 通過它我們將文字顏色設定為紅色,並使用屬性 -fx-background-color: yellow 將背景顏色設定為黃色。

編譯上述示例程式碼並在你的環境中執行後,你將獲得以下輸出。

輸出:

使用 setStyle() 方法通過 JavaFx 庫在 Java 中為文字標籤著色

改變標籤文字顏色的其他方法

JavaFX 支援適用於 FXML 的 CSS。現在,在使用 Oracle 提供的 Scene Builder 等 JavaFX GUI 構建工具設計使用者介面時,你可以在開發 UI 時輕鬆地使用 CSS 屬性定義文字顏色。

此外,你可以新增一個 CSS 檔案,你可以在該檔案上新增以下兩個屬性。

-fx-text-fill: red;
-fx-background-color: yellow;

你可以使用下面的程式碼將你的 CSS 檔案直接包含在你的程式碼中。

程式碼:

scene.getStylesheets().add("YourCSS.css")

請記住,如果你的 IDE 不支援自動包含庫和包。然後你可能需要在編譯之前手動包含這些必要的庫和包。

作者: MD Aminul Islam
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

相關文章 - Java JavaFx