如何从Javafx2 HTMLEditor获取文本

时间:2014-05-19 10:47:55

标签: java javafx-2 html-editor

我有一个HTMLEditor,我输入了"我的简单文字"。

 @FXML
 public HTMLEditor htmlEditor;

当说

htmlEditor.getHtmlText();

此回归

<html><head></head><body contenteditable="true"><p style="text-align: left;"><font face="'Segoe UI'">My Simple Text</font></p></body></html>

但是想要没有html标签的文本,即

My Simple Text

how can i do it?

4 个答案:

答案 0 :(得分:4)

Jsoup实际上很简单。

public static String html2text(String html) {
    return Jsoup.parse(html).text();
}

来源: Remove HTML tags from a String

答案 1 :(得分:2)

在HtmlEditor上应用 getHtmlText()后,将生成的html代码字符串传递给以下方法:

public static String getText(String htmlText) {

  String result = "";

  Pattern pattern = Pattern.compile("<[^>]*>");
  Matcher matcher = pattern.matcher(htmlText);
  final StringBuffer text = new StringBuffer(htmlText.length());

  while (matcher.find()) {
    matcher.appendReplacement(
      text,
      " ");
  }

  matcher.appendTail(text);

  result = text.toString().trim();  

  return result;
}

答案 2 :(得分:1)

您应该从您从此HTMLEditor获取的Html Text中删除所有html标记。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;


public class HTMLEditorDemo extends Application {

    @Override
    public void start(Stage primaryStage) {

        HTMLEditor editor = new HTMLEditor();
        Button b = new Button("Show Text");
        b.setOnAction((ActionEvent e) -> {
            String htmlText = editor.getHtmlText();
            stripHTMLTags(htmlText);

        });

        VBox vBox = new VBox(b, editor);
        Scene scene = new Scene(vBox, 800, 600);


        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    private void stripHTMLTags(String htmlText) {

        Pattern pattern = Pattern.compile("<[^>]*>");
        Matcher matcher = pattern.matcher(htmlText);
        final StringBuffer sb = new StringBuffer(htmlText.length());
        while(matcher.find()) {
            matcher.appendReplacement(sb, " ");
        }
        matcher.appendTail(sb);
        System.out.println(sb.toString().trim());

    }

}

帕特里克

答案 3 :(得分:0)

尝试一下

 WebView webView = (WebView) htmlEditor.lookup("WebView");
    ((HTMLBodyElementImpl) ((NodeListImpl) webView.getEngine().getDocument().getElementsByTagName("body")).item(0)).getTextContent();

您还可以设置内容文本或专注于Webview