如何使用 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);
}
}输出
在执行时,它将产生以下输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP