从JTextPane获取原始文本 [英] Getting raw text from JTextPane
问题描述
在我的应用程序中,我使用 JTextPane
来显示一些日志信息。由于我想高亮显示本文中的某些特定行(例如错误消息),我将 contentType
设置为 text / html
。这样,我可以格式化我的文本。
In my application, I use a JTextPane
to display some log information. As I want to hightlight some specific lines in this text (for example the error messages), I set the contentType
as "text/html
". This way, I can format my text.
现在,我创建一个JButton,复制此 JTextPane的内容
进入剪贴板。这部分很简单,但我的问题是,当我调用 myTextPane.getText()
时,我会得到HTML代码,例如:
Now, I create a JButton that copies the content of this JTextPane
into the clipboard. That part is easy, but my problem is that when I call myTextPane.getText()
, I get the HTML code, such as :
<html>
<head>
</head>
<body>
blabla<br>
<font color="#FFCC66"><b>foobar</b></font><br>
blabla
</body>
</html>
而不是仅获取原始内容:
instead of getting only the raw content:
blabla
foobar
blabla
有没有办法只用纯文本获取我的 JTextPane
的内容?或者我是否需要自己将HTML转换为原始文本?
Is there a way to get only the content of my JTextPane
in plain text? Or do I need to transform the HTML into raw text by myself?
推荐答案
根据接受的答案:从Java字符串中删除HTML
MyHtml2Text parser = new MyHtml2Text();
try {
parser.parse(new StringReader(myTextPane.getText()));
} catch (IOException ee) {
//handle exception
}
System.out.println(parser.getText());
找到 Html2Text
类的略微修改版本关于答案我链接到
Slightly modified version of the Html2Text
class found on the answer I linked to
import java.io.IOException;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
public class MyHtml2Text extends HTMLEditorKit.ParserCallback {
StringBuffer s;
public MyHtml2Text() {}
public void parse(Reader in) throws IOException {
s = new StringBuffer();
ParserDelegator delegator = new ParserDelegator();
delegator.parse(in, this, Boolean.TRUE);
}
public void handleText(char[] text, int pos) {
s.append(text);
s.append("\n");
}
public String getText() {
return s.toString();
}
}
如果您需要更精细的处理,请考虑实施更多由定义的界面 HTMLEditorKit.ParserCallback
If you need a more fine-grained handling consider implementing more of the interface defined by HTMLEditorKit.ParserCallback
这篇关于从JTextPane获取原始文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!