Java getting text content from an element to include line breaks

1.5k views Asked by At

I have an Element which I got from the Document of a WebEngine (JavaFX) and I use its getTextContent() function from the body element to get the text content. The body element has the attribute contenteditable="true" so I can write on it. However the string returned from getTextContent() doesn't include line breaks. So

Line 1
Line 2
Line 3

On the body would return Line 1Line 2Line 3 I need it to include line breaks. How can I get it to do this?

Alternatively, I could use <TextArea> instead of <body contenteditable="true" if I can find a way to style each character. But I don't know how.

Thanks.

1

There are 1 answers

1
James_D On BEST ANSWER

Subsequent lines will be inserted into the html as new <div> elements that are children of the <body> element.

You can see the HTML content by executing a snippet of javascript:

String html = (String)webView.getEngine()
    .executeScript("document.documentElement.innerHTML");

To get the individual lines, you need to iterate through the <body>'s child nodes. Here's an example:

import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class EditableWebView extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        webView.getEngine().loadContent(
            "<html><body contentEditable=\"true\"></body></html>");

        Button contentButton = new Button("Show content");
        contentButton.setOnAction(e -> {
            List<String> lines = new ArrayList<>();

            Node body = webView.getEngine()
                    .getDocument()
                    .getElementsByTagName("body")
                    .item(0);
            NodeList childNodes = body.getChildNodes();
            for (int i=0; i<childNodes.getLength(); i++) {
                lines.add(childNodes.item(i).getTextContent());
            }

            lines.forEach(System.out::println);

        });

        Button htmlButton = new Button("Show HTML");
        htmlButton.setOnAction(e -> 
            System.out.println(webView.getEngine()
                    .executeScript("document.documentElement.innerHTML")));

        HBox buttons = new HBox(5, contentButton, htmlButton);

        BorderPane root = new BorderPane(webView, null, null, buttons, null);
        Scene scene = new Scene(root, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

If you want other options for creating styleable editable text, have a look at RichTextFX