JavaFX TextArea 如何设置带有自动换行符的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35797493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX TextArea how to set text with automatic new line breaks
提问by RichardK
In my application, I'm using two Tabs. In the first I placed HtmlEditor and in the second one I placed TextArea. HTML tab is default and when user is creating HTML input, he can switch into TextArea to see / change the HTML source code directly. I've added a listener to get rhe htmlText from the HtmlEditor and set it as text in TextArea, so user can easily switch between HTML and source mode. Here's my listener:
在我的应用程序中,我使用了两个选项卡。在第一个中我放置了 HtmlEditor,在第二个中放置了 TextArea。HTML 选项卡是默认的,当用户创建 HTML 输入时,他可以切换到 TextArea 直接查看/更改 HTML 源代码。我添加了一个监听器来从 HtmlEditor 获取 htmlText 并将其设置为 TextArea 中的文本,因此用户可以轻松地在 HTML 和源模式之间切换。这是我的听众:
@FXML
private Tab htmlTab;
@FXML
private Tab sourceTab;
@FXML
private HTMLEditor htmlEditor;
@FXML
private TextArea textEditor;
htmlTab.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (htmlTab.isSelected()) {
htmlEditor.setHtmlText(textEditor.getText());
}
}
});
sourceTab.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (sourceTab.isSelected()) {
textEditor.setText(htmlEditor.getHtmlText());
}
}
});
It works fine, but HtmlEditor is breaking text into lines automatically. When I switch to TextArea, it's all in one line.
它工作正常,但 HtmlEditor 会自动将文本分成几行。当我切换到 TextArea 时,所有内容都在一行中。
I thought about making a helper method which takes TextArea length attribute to count number of chars and adds new line character every "n" character, but maybe there is a better solution?
我想过制作一个辅助方法,它采用 TextArea 长度属性来计算字符数并每“n”个字符添加新行字符,但也许有更好的解决方案?
采纳答案by James_D
If you just want the text to wrap, use
如果您只想让文本换行,请使用
textEditor.setWrapText(true);