1

JTextPane を使用して、ローカルに保存された画像を含む基本的な HTML コンテンツを表示しています。テキストペインの入力属性を使用して JTextPane のスタイルを設定しようとしています。ペインのスタイルを変更するたびに、スタイリング コードをコメント アウトしないと、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 として一度に挿入し、すべて同じ方法でスタイルを設定するので、私にとっては有効な唯一の方法でした。他の方法はうまくいかなかったので、このパネルのスタイリング方法を維持できることを願っています。

4

1 に答える 1

1

setCharacterAttributes()最後の引数 ( replace ) を指定してメソッドを呼び出すtrueと、画像に関連する HTML コードがいくらか消去されます。

単にそれを呼び出すだけfalseで動作します:

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

スタイル付きテキストで表示される画像

于 2014-02-08T21:37:58.367 に答える