我需要显示多行只读文本 - 可以使用哪个控件?它应该只显示文本,就像标签一样,但是标签不支持多行?
感谢您的任何提示:-)
Label
中显示多行只读文本。
如果文本中包含
\n
(换行符)字符,则标签将在换行符所在的位置换行。
wrapText
设置为 true 并且没有足够的空间来显示单行文本,则标签会将文本换行。
如果您想要不同样式的文本,那么,如果使用 JavaFX 2,请将多个标签放置在
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");
}
尝试运行上述程序并调整窗口大小,以查看标签文本中的
\n
新行值以及标签上的 wrapText
属性的效果。将 wrapText
设置从 true 更改为 false,以查看打开和关闭 wrapText
之间的差异。
如果您为
Label
设置了所需的最大宽度,则将 setWrapText
设置为 true
,以便显示多行文本:
Label label = new Label("Your long text here");
label.setMaxWidth(180);
label.setWrapText(true);
Text
来显示多行,根据您的需要设置 wrappingWidthProperty
。
Text text = new Text();
text.wrappingWidthProperty().set(345);
在这段代码中,我将最大宽度设置为
345.0
,因此当文本大小超过 345
时,像素将换行到下一行。
如果文字有 (换行)字符,那么标签将在换行符所在的位置换行到新行。
当您从 FXML 文件以及可视化 FXML 编辑器设置文本时,它不起作用。
还提供文本课程。这个答案中有一个很好的解释label-and-text-differences-in-javafx基本上在没有输入的地方使用Text,否则标签更好。
对于我们这里的 FXML 用户,我从 Steel Rat 的 answer 的评论中学到了什么。
FXML:
<Label text="one line second line" />
如果您想在场景生成器中输入此内容,请按“文本”字段右侧的小齿轮。在上下文菜单中选择“切换到多行模式”。 (在20.0.0版本测试)