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 として一度に挿入し、すべて同じ方法でスタイルを設定するので、私にとっては有効な唯一の方法でした。他の方法はうまくいかなかったので、このパネルのスタイリング方法を維持できることを願っています。