JavaFX TextArea how to set text with automatic new line breaks

微笑、不失礼 提交于 2019-12-08 16:53:34

问题


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:

@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.

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?


回答1:


If you just want the text to wrap, use

textEditor.setWrapText(true);


来源:https://stackoverflow.com/questions/35797493/javafx-textarea-how-to-set-text-with-automatic-new-line-breaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!