1

JTextPaneを使用して会話を表示するチャットクライアントを構築しようとしています。ユーザーが選択したチャット参加者の過去の文章を強調表示するのに問題があります。これを実装するときは、コンテンツの一部がHTMLである必要があるため、HTMLDocumentの使用に固執する必要があります。

最良のアイデアは、会話に参加するユーザーごとに異なる名前のスタイルを使用することであるように思われました。特定の人のテキストを強調表示する必要がある場合、私は彼の個人的なスタイルを更新するだけで、彼が言ったことはすべて魔法のように強調表示されるはずです。残念ながら、これは機能しません。

したがって、テキストを追加するには、次のようにします。

public void addMessage(String from, String message){
    HTMLDocument doc = (HTMLDocument) textPane.getStyledDocument();
    if(doc != null){
        try {
            String stylename = "from_" + from;
            if(textPane.getStyle(stylename) == null){
                LOG.debug("Did not find style. Adding new: " + stylename);
                Style nameStyle = textPane.addStyle(stylename, null);
                StyleConstants.setForeground(nameStyle, Color.black);
                StyleConstants.setBold(nameStyle, true);
            }else{
                LOG.debug("Found existing style: " + textPane.getStyle(stylename));
            }
            doc.insertString(doc.getLength(), from + ": ", textPane.getStyle(stylename));
            doc.insertString(doc.getLength(), message + "\n", null);
        } catch (BadLocationException ble) {
            LOG.error("Could not insert text to tab");
        }
    }
}

これまでのところ良い...テキストは私が望むようにtextPaneに表示されます。ただし、将来、スタイルシートを更新して呼び出しようとすると、次のようになります。

public void highlight(String name, boolean highlight){
    Style fromStyle = textPane.getStyle("from_" + name);
    if(fromStyle != null){
        LOG.debug("found style, changing color");
        StyleConstants.setForeground(fromStyle, Color.red);
    }else{
        LOG.debug("fromStyle was NULL");
    }
}

..スタイルが見つかり、コードが実行されていることがわかりますが、画面上では何も変更されていません。

この問題を解決する方法について何か提案がありますか。名前付きスタイルでこれを機能させる方法はありますか、それともまったく異なるアプローチを取る必要がありますか?

ありがとうございました

4

2 に答える 2

1

Styleオブジェクトを変更したばかりですが、Styleを使用して変更を適用する必要がありますsetCharacterAttributes

于 2011-05-09T20:53:22.350 に答える
1

それ以来、私は自分に合ったソリューションを作成しました。興味のある人のために、機能するテストケースをここに投稿します。最終的に、StyleSheetのスタイルクラスを更新してから、すべての段落要素に対してhtmlDocument.setParagraphAttributesを呼び出すという解決策になりました。

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

public class StyleChangeTest extends JFrame {

    public final static int APP_WIDTH = 640;
    public final static int APP_HEIGHT = 400;
    public JTextPane jTextPane;
    public StyleSheet styleSheet;
    public HTMLDocument htmlDocument;
    public HTMLEditorKit htmlEditorKit;
    public Element bodyElement;

    public static StyleChangeTest jTextPaneApp;

    public static void main(String[] args) throws InterruptedException, InvocationTargetException{
        EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                try {
                    jTextPaneApp = new StyleChangeTest();
                    jTextPaneApp.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("Started");
        Thread.currentThread().sleep(1000);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    jTextPaneApp.change();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("Finished");
    }

    public StyleChangeTest(){
        setSize(APP_WIDTH, APP_HEIGHT);
        setResizable(false);
        setTitle("JTextPane App");

        styleSheet = new StyleSheet();
        styleSheet.addRule(".someclass1 {color: blue;}");
        styleSheet.addRule(".someclass2 {color: green;}");

        htmlEditorKit = new HTMLEditorKit();
        htmlEditorKit.setStyleSheet(styleSheet);
        htmlDocument = (HTMLDocument) htmlEditorKit.createDefaultDocument();
        jTextPane = new JTextPane();
        jTextPane.setEditorKit(htmlEditorKit);
        jTextPane.setDocument(htmlDocument);

        try {
            Element htmlElement = htmlDocument.getRootElements()[0];
            bodyElement = htmlElement.getElement(0);

            Container contentPane = getContentPane();
            contentPane.setLayout(new BorderLayout());
            contentPane.add(jTextPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e){
                    System.exit(0);
                }
            });

            addContent("<font class=someclass1>test 1</font><br>");
            addContent("<font class=someclass2>test 2</font><br>");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void reapplyStyles() {
        System.out.println("Reformating...");
        Element sectionElem = bodyElement.getElement(bodyElement.getElementCount() - 1);
        int paraCount = sectionElem.getElementCount();
        for (int i=0; i<paraCount; i++) {
            Element paraElem = sectionElem.getElement(i);
            //System.out.println("\tParagraph: " + (i+1) + " - " + paraElem);
            int rangeStart = paraElem.getStartOffset();
            int rangeEnd = paraElem.getEndOffset();
            htmlDocument.setParagraphAttributes(rangeStart, rangeEnd-rangeStart, paraElem.getAttributes(), true);
        }
    }


    public void change() throws BadLocationException, IOException{
        styleSheet = htmlEditorKit.getStyleSheet();
        styleSheet.addRule(".someclass1 {color: red;}");
        reapplyStyles();
        addContent("<font class=someclass1>test 3</font><br>");
    }


    private void addContent(String content) throws BadLocationException, IOException{
        Element contentElement = bodyElement.getElement(bodyElement.getElementCount() - 1);

        StringBuffer sbHtml = new StringBuffer();
        sbHtml.append("<font class=someclass>" + content + "</font><br>");

        htmlDocument.insertBeforeEnd(contentElement, sbHtml.toString());
    }

}
于 2011-07-30T13:36:44.453 に答える