[英]how get Only text from Javafx2 HTMLEditor
I have a HTMLEditor and i have typed "My Simple Text". 我有一个HTMLEditor,我输入了“我的简单文字”。
@FXML
public HTMLEditor htmlEditor;
when say 什么时候说
htmlEditor.getHtmlText();
this return 这回归
<html><head></head><body contenteditable="true"><p style="text-align: left;"><font face="'Segoe UI'">My Simple Text</font></p></body></html>
But want text without html tag ie 但想要没有html标签的文本即
My Simple Text
how can i do it?
This is actually dead simple with Jsoup . 这对Jsoup来说实际上很简单。
public static String html2text(String html) {
return Jsoup.parse(html).text();
}
source : Remove HTML tags from a String source: 从String中删除HTML标记
After applying getHtmlText() on your HtmlEditor pass the resulted String of html code to the following method: 在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;
}
You should remove all html tags from your Html Text you get from this HTMLEditor. 您应该从您从此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());
}
}
Patrick 帕特里克
Try this 试试这个
WebView webView = (WebView) htmlEditor.lookup("WebView");
((HTMLBodyElementImpl) ((NodeListImpl) webView.getEngine().getDocument().getElementsByTagName("body")).item(0)).getTextContent();
you can also set to content text or focus on webview 您还可以设置内容文本或关注webview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.