我一直在使用 JTextPane 来显示基本的 HTML 内容,包括本地保存的图像。我一直在尝试使用文本 Pane 的输入属性来设置 JTextPane 的样式。每当我修改 Pane 的样式时,如果不注释掉样式代码,我所拥有的 HTML 图像就会中断并且不会出现。
这是代码的 SSCE:
import java.awt.Color;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class JTextPaneImageTest {
public static void main(String[] args) {
new JTextPaneImageTest();
}
public JTextPaneImageTest() {
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setEditable(false);
String content = "<html><body><p>Test text here</p>"
+ "<img src=\"file:\\\\\\C:\\Users\\racha_000\\AppData\\Local\\Temp\\ebookr\\test.jpg\" />"
+ "</body></html>";
System.out.println(content);
HTMLEditorKit editorKit = (HTMLEditorKit) textPane.getEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) textPane.getDocument();
MutableAttributeSet mats = textPane.getInputAttributes();
StyleConstants.setForeground(mats, Color.RED);
try {
editorKit.insertHTML(htmlDoc, htmlDoc.getLength(), content, 0, 0, null);
} catch (BadLocationException | IOException e) {
e.printStackTrace();
} finally {
htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, true);
}
JFrame frame = new JFrame();
frame.add(textPane);
frame.setVisible(true);
}
}
需要注意的重要代码是,每当更改可变属性集和字符属性集时,图像都不起作用。
MutableAttributeSet mats = textPane.getInputAttributes();
StyleConstants.setForeground(mats, Color.RED);
htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, true);
没有样式:
带有样式:
以这种方式设置文档样式是唯一对我有用的方法,因为我将所有内容一次性插入为 HTML 并以相同的方式设置样式。其他方法不起作用,所以我希望能够保留这种面板样式设置方法。
最佳答案
调用 setCharacterAttributes()
方法并将其最后一个参数(replace)设置为 true
会在一定程度上删除与图像相关的 HTML 代码。
只需使用 false
调用它即可工作:
htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, false);
关于java - 无法设置 JTextPane 样式并同时显示 HTML 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651765/