如何将文本 append 到 webengine?我试过这个:
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);
}
但文件是
null
最佳答案
首先,如果 webengine 无法加载内容或您调用 engine.getDocument()
,Document 将返回 null。在内容完全完成加载之前。
二、doc.getElementById("body")
搜索 ID 为“body”的 DOM 元素。但是,您加载的内容根本没有这样的 id 或任何 id。
为了更好地理解这些,这里有一个完整的可运行示例,请单击按钮:
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);
}
}
请注意,我在主体中放置了一个 id=content 的 div,所以
doc.getElementById("content")
返回那个 div。
关于dom - append 文本 WebEngine - JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13719669/