8

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」コンテンツ タイプを適用することは可能ですか? これがなければ、非常に複雑なアルゴリズムを実装せずにメッセージを処理することはほとんど不可能です。

4

3 に答える 3

12

テキストを追加するために insertString() メソッドを使用するべきではないと思います。次のようなものを使用する必要があると思います。

JTextPane textPane = new JTextPane();
textPane.setContentType( "text/html" );
textPane.setEditable(false);
HTMLDocument doc = (HTMLDocument)textPane.getDocument();
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
String text = "<a href=\"abc\">hyperlink</a>";
editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null);
于 2013-02-27T22:32:23.730 に答える
3

再編集

申し訳ありませんが、文字列を HTML として挿入するという問題を誤解していました。そのためには、HTMLEditorKit 機能に頼る必要があります。

            StyledDocument styleDoc = textPane.getStyledDocument();
            HTMLDocument doc = (HTMLDocument)styleDoc;
            Element last = doc.getParagraphElement(doc.getLength());
            try {
                doc.insertBeforeEnd(last, messages[1] + "<br>");
            } catch (BadLocationException ex) {
            } catch (IOException ex) {
            }
于 2013-02-27T21:25:51.490 に答える
1

これを行うためのはるかに簡単な方法を次に示します。

JTextPane pane = new JTextPane();
pane.setContentType("text/html");

pane.setText("<html><h1>My First Heading</h1><p>My first paragraph.</p></body></html>");
于 2015-07-02T00:37:14.403 に答える