JavaFX标签

JavaFX API的javafx.scene.control包中的Label类可用于显示一个文本元素。
我们可以包装文本元素以适应特定空间,添加图形图像或使用JavaFX Label控件应用视觉效果。

以下代码显示如何使用Label显示文本。

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
    
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root, 300, 130, Color.WHITE);
        
        GridPane gridpane = new GridPane();
        gridpane.setPadding(new Insets(5));
        gridpane.setHgap(10);
        gridpane.setVgap(10);
        
        Label label = new Label("Label");
        GridPane.setHalignment(label, HPos.CENTER);
        gridpane.add(label, 0, 0);
        
        root.getChildren().add(gridpane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

创建标签

JavaFX API提供了Label类的三个构造函数来创建标签。

//An empty label
Label label1 = new Label();

//A label with the text element
Label label2 = new Label("Name");

//A label with the text element and graphical icon
Image image = new Image("01.png");
Label label3 = new Label("Name", new ImageView(image));

标签内容

创建标签后,我们可以使用Label类中的以下方法添加文本和图形内容。

  • setText(String text) - 设置标签的文本标题
  • setGraphic(Node graphic) - 设置图形图标

setGraphicTextGap()方法设置文本和图标之间的间距。setTextFill()方法设置标签文本的颜色。以下代码创建文本标签,向其添加图标,并为文本设置填充颜色。

Label label1 = new Label("Name");
Image image = new Image("01.png");
label1.setGraphic(new ImageView(image));
label1.setTextFill(Color.web("#FF76a3"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值