Append text WebEngine - JavaFX

Lukasz picture Lukasz · Dec 5, 2012 · Viewed 7.2k times · Source

How can I append text to webengine? I tried this:

public TabMessage(String title) {
    super(title);
    view = new WebView();
    engine = view.getEngine();
    engine.loadContent("<body></body>");
    view.setPrefHeight(240);
}

private void append(String msg){
    Document doc = engine.getDocument();
    Element el = doc.getElementById("body");
    String s = el.getTextContent();
    el.setTextContent(s+msg);
}

But document is null

Answer

Uluk Biy picture Uluk Biy · Dec 5, 2012

First, Document returns null if webengine fails to load the content or you call engine.getDocument() before the content is fully finished its loading.

Second, doc.getElementById("body") searches for the DOM element with id "body". However the loaded content by you has no such id or any id at all.

To understand these better here is a complete runnable example, click on the button:

package demo;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Demo extends Application {

    private WebView view;
    private WebEngine engine;

    @Override
    public void start(Stage primaryStage) {

        view = new WebView();
        engine = view.getEngine();
        engine.loadContent("<body><div id='content'>Hello </div></body>");
        view.setPrefHeight(240);

        Button btn = new Button("Append the \"World!\"");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                append(" \"World!\"");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().addAll(view, btn);
        Scene scene = new Scene(root, 300, 250);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void append(String msg) {
        Document doc = engine.getDocument();
        Element el = doc.getElementById("content");
        String s = el.getTextContent();
        el.setTextContent(s + msg);
    }

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

Note that I have put a div with id=content in th body so doc.getElementById("content") returns that div.