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