setContentType("text/html") を設定すると、JTextPane.setText() で設定されたテキストにのみ適用されます。スタイルを介して JTextPane に配置される他のすべてのテキストは、コンテンツ タイプの影響を受けません。
これが私が意味することです:
private final String[] messages = {"first msg", "second msg <img src=\"file:src/test/2.png\"/> yeah", "<img src=\"file:src/test/2.png\"/> third msg"};
public TestGUI() throws BadLocationException {
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
//Read all the messages
StringBuilder text = new StringBuilder();
for (String msg : messages) {
textext.append(msg).append("<br/>");
}
textPane.setText(text.toString());
//Add new message
StyledDocument styleDoc = textPane.getStyledDocument();
styleDoc.insertString(styleDoc.getLength(), messages[1], null);
JScrollPane scrollPane = new JScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//add scrollPane to the main window and launch
//...
}
一般に、JTextPane で表されるチャットがあります。サーバーからメッセージを受信し、それらを処理します。特定のケースに合わせてテキストの色を設定し、スマイル マーカーを画像パスに変更します。すべてが HTML の範囲内で行われます。しかし、上記の例から明らかなように、setText のみが setContentType("text/html") の対象であり、追加された新しいメッセージが "text/plain" で表される 2 番目の部分です (私が間違っていなければ)。 )。
JTextPane に挿入されるすべてのデータに「text/html」コンテンツ タイプを適用することは可能ですか? これがなければ、非常に複雑なアルゴリズムを実装せずにメッセージを処理することはほとんど不可能です。