如何在 JavaFX 中换行显示标签文本?
您可以使用 Label 组件在用户界面上显示文本元素/图片。它是一种不可编辑的文本控件,主要用于说明应用程序中其他节点的用途。
在 JavaFX 中,您可以通过实例化 javafx.scene.control.Label 类来创建一个标签。要创建一个标签,您需要实例化此类。
一旦您创建了一个标签,就可以使用 setMaxWidth() 和 setMaxHeight() 方法分别设置它的最大宽度和高度。
一旦您设置了标签的最大宽度,其超出指定宽度的内容将被截断。
为了避免这种情况,您可以换行显示指定宽度内的文本,您需要调用 setWrapText() 方法。向此方法传递 true 作为参数时,超出指定宽度的标签内容将换行到下一行。
示例
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class LabelWrapExample extends Application {
public void start(Stage stage) {
String text = "Tutorials Point originated from the idea that there exists a class
of readers who respond better to online content and prefer to learn new skills at
their own pace from the comforts of their drawing rooms.";
//Creating a Label
Label label = new Label(text);
//wrapping the label
label.setWrapText(true);
//Setting the alignment to the label
label.setTextAlignment(TextAlignment.JUSTIFY);
//Setting the maximum width of the label
label.setMaxWidth(200);
//Setting the position of the label
label.setTranslateX(25);
label.setTranslateY(25);
Group root = new Group();
root.getChildren().add(label);
//Setting the stage
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Label Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP