如何在JavaFX中包装标签的文本?
为避免这种情况,您可以将文本包装在指定的宽度内,您需要调用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 = "nhooo.com 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."; //创建标签 Label label = new Label(text); //包装标签 label.setWrapText(true); //将对齐方式设置为标签 label.setTextAlignment(TextAlignment.JUSTIFY); //设置标签的最大宽度 label.setMaxWidth(200); //设置标签的位置 label.setTranslateX(25); label.setTranslateY(25); Group root = new Group(); root.getChildren().add(label); //设置舞台 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); } }
输出结果