如何在JavaFX中添加换行符以提示文本?

时间:2018-08-05 22:06:19

标签: java javafx

我有一个TextArea,其中有一些提示文本,我想将其拆分为几行,但是由于某些原因,换行符在提示文本中不起作用。

代码:

TextArea paragraph = new TextArea();
paragraph.setWrapText(true);
paragraph.setPromptText(
    "Stuff done today:\n"
    + "\n"
    + "- Went to the grocery store\n"
    + "- Ate some cookies\n"
    + "- Watched a tv show"
);

结果:

enter image description here

如您所见,文本未正确换行。有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

该提示在内部由Text类型的节点显示,该节点可以处理换行符。所以有趣的问题是为什么它们不显示?通过查看hintText属性可以揭示原因:它用空字符串静默替换所有\n

private StringProperty promptText = new SimpleStringProperty(this, "promptText", "") {
    @Override protected void invalidated() {
        // Strip out newlines
        String txt = get();
        if (txt != null && txt.contains("\n")) {
            txt = txt.replace("\n", "");
            set(txt);
        }
    }
};

一种解决方法(不确定它是否在所有平台上都可以工作-对我有帮助)是改为使用\r

paragraph.setPromptText(
    "Stuff done today:\r"
    + "\r"
    + "- Went to the grocery store\r"
    + "- Ate some cookies\r"
    + "- Watched a tv show"
);
相关问题