java - 无法设置 JTextPane 样式并同时显示 HTML 图像

标签 java swing jtextpane styleddocument

我一直在使用 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);

没有样式:

Without Styling

带有样式:

With Styling

以这种方式设置文档样式是唯一对我有用的方法,因为我将所有内容一次性插入为 HTML 并以相同的方式设置样式。其他方法不起作用,所以我希望能够保留这种面板样式设置方法。

最佳答案

调用 setCharacterAttributes() 方法并将其最后一个参数(replace)设置为 true 会在一定程度上删除与图像相关的 HTML 代码。

只需使用 false 调用它即可工作:

htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, false);

image displayed with styled text

关于java - 无法设置 JTextPane 样式并同时显示 HTML 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651765/

相关文章:

java - 在 JTextPane 中插入一些字符会导致性能问题和内存泄漏

java - Jtextpane 复制彩色文本并粘贴

java - 如何从 Liferay MVC Portlet 触发自动登录

java - 我无法在 elasticsearch 中将地理点设置为 null

java - 更改 JButton 的图标

java - JTextPane 每次我插入字符串时都会添加大空格

java - Lighttpd 运行在 Android 服务上

Java类引用类的加载机制

java - 如何外部化 MouseListener?

java - 将项目添加到 JTable 的数组中