繁体   English   中英

如何从Javafx2 HTMLEditor获取文本

[英]how get Only text from Javafx2 HTMLEditor

我有一个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?

这对Jsoup来说实际​​上很简单。

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

source: 从String中删除HTML标记

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

您应该从您从此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());

    }

}

帕特里克

试试这个

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

您还可以设置内容文本或关注webview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM