Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX TextArea how to set text with automatic new line breaks

In my application, I'm using two Tabs. In the first one I placed a HtmlEditor and in the second one I placed a TextArea. HTML tab is default and when user is creating HTML input, he can switch to TextArea in order to see or change the HTML source code directly. I've added a listener to get the 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" characters, but maybe there is a better solution?

like image 863
RichardK Avatar asked Mar 04 '16 13:03

RichardK


People also ask

How do you insert a line break in textarea?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.

How do I preserve line breaks when getting text from a textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How do I make a textarea not editable in Javafx?

In FXML, add editable="false" to your TextField tag. Or uncheck the "Editable" checkbox in Scene Builder.


1 Answers

If you just want the text to wrap, use

textEditor.setWrapText(true);
like image 118
James_D Avatar answered Oct 21 '22 17:10

James_D