jew*_*sea 65
您可以在a中显示多行只读文本Label.
如果文本中包含\n(换行符)字符,则无论换行符在何处,标签都将换行到新行.
如果标签wrapText设置为true且没有足够的空间显示单行文本,则标签会将文本换行到新行.
如果您想要不同样式的文本,那么,如果您使用JavaFX 2,请在a中放置多个标签FlowPane,如果您使用的是Java 8+,则将标签放在一个TextFlow组件中.

由以下代码生成:
import javafx.scene.Scene;
import javafx.application.Application;
import javafx.scene.control.Label;
import javafx.scene.image.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LoveMeNot extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
Label label = new Label(WORDS);
label.setWrapText(true);
label.setStyle("-fx-font-family: \"Comic Sans MS\"; -fx-font-size: 20; -fx-text-fill: darkred;");
ImageView image = new ImageView(IMAGE);
image.setOpacity(0.3);
StackPane layout = new StackPane();
layout.setStyle("-fx-background-color: mistyrose; -fx-padding: 10;");
layout.getChildren().setAll(image, label);
stage.setTitle("Love Me Not");
stage.setScene(new Scene(layout));
stage.show();
}
// creates a triangle.
private static final String WORDS =
"Love not me for comely grace,\n" +
"For my pleasing eye or face,\n" +
"Nor for any outward part,\n" +
"No, nor for my constant heart,\n" +
"For these may fail, or turn to ill.\n" +
"So thou and I must sever.\n" +
"Keep therefore a true woman’s eye,\n" +
"And love me still, but know not why,\n" +
"So hast thou the same reason still\n" +
"To doat upon me ever.";
private static final Image IMAGE =
new Image("http://icons.iconarchive.com/icons/artdesigner/gentle-romantic/256/rose-icon.png");
}
Run Code Online (Sandbox Code Playgroud)
尝试运行上述程序并调整窗口大小,以查看\n标签文本中新行值的效果以及标签上的wrapText属性.将wrapText设置从true变为false,以查看wrapText打开和关闭之间的区别.
您也可以使用Text以多行显示,wrappingWidthProperty根据您的需要进行设置。
Text text = new Text();
text.wrappingWidthProperty().set(345);
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我将最大宽度设置为345.0,因此当文本的大小超出345像素时,将被换行到下一行。
小智 6
如果文本中包含\n(换行符)字符,那么标签将在换行符所在的位置将换行放置到新行.
当您从FXML文件以及Visual FXML编辑器设置文本时,它不起作用.
小智 5
如果您为设置了最大宽度Label,则将其设置setWrapText为,true以便显示多行文字:
Label label = new Label("Your long text here");
label.setMaxWidth(180);
label.setWrapText(true);
Run Code Online (Sandbox Code Playgroud)