0

我有一个ElementDocumenta WebEngine(JavaFX) 中得到的,我使用它getTextContent()从 body 元素中获取的函数来获取文本内容。body 元素有这个属性contenteditable="true",所以我可以在上面写。但是,从返回的字符串getTextContent()不包括换行符。所以

Line 1
Line 2
Line 3

在身体上会返回Line 1Line 2Line 3我需要它包括换行符。我怎样才能让它做到这一点?

或者,如果我能找到一种方法来设置每个字符的样式,我可以使用<TextArea>而不是。<body contenteditable="true"但我不知道怎么做。

谢谢。

4

1 回答 1

1

随后的行将作为新元素插入到 html 中,这些新<div>元素是元素的子<body>元素。

您可以通过执行一段 javascript 来查看 HTML 内容:

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

要获取各个行,您需要遍历<body>的子节点。这是一个例子:

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);
    }
}

如果您想要其他选项来创建可设置样式的可编辑文本,请查看RichTextFX

于 2014-11-22T14:48:14.817 回答