如何使用 JavaFX 新增影像作為標籤?


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

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

您可以使用 setGraphic() 方法將圖形物件用作標籤 Label 類的(從 javafx.scene.control.Labeled 類繼承的)。此方法接受表示圖形(圖示)的 Node 類的物件。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
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 ImageAsLabel extends Application {
   public void start(Stage stage) {
      // Creating a Label
      Label label = new Label("Sample label");
     
      // Creating a graphic (image)
      Image img = new Image("UIControls/logo.png");
      ImageView view = new ImageView(img);
      view.setFitHeight(80);
      view.setPreserveRatio(true);
      label.setGraphic(view);
     
      // 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, 200, Color.BEIGE);
      stage.setTitle("Label Example");
      stage.setScene(scene);
      stage.show();
   }
   
   public static void main(String args[]){
      launch(args);
   }
}

輸出

在執行時,它將產生以下輸出

更新於: 19-4-2022

3K+ 瀏覽

開始你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.