javaswingfontsjtextpanestyleddocument

How to preserve style of texts in JTextPane while append strings


Hi I have JTextPane and I want to load contents (text with font information) in different time. the appending text will always change in Font name or size or bold or italic. When I inserted new string(with diff fonts), TextPane always loosing font information of a previous loaded text. How to preserve font information always for a text pane? Also I want to insert images!! Do I have to use HtmlDocument for that? Any idea or suggestions are most welcome. Thanks in advance!! My code for JTextPane is,

textPane.setText("\n This is sample text editor ex");
styleDoc = textPane.getStyledDocument();
SimpleAttributeSet keyWord = new SimpleAttributeSet();
// set font information for new text
StyleConstants.setFontFamily(keyWord, fontName);
StyleConstants.setFontSize(keyWord, fontSize);
try {
            styleDoc.insertString(0,
                    styleDoc.getText(0, styleDoc.getLength()), null);
            styleDoc.insertString(styleDoc.getLength(), "ample", keyWord);
        } catch (Exception e) {
            e.printStackTrace();
        }

Solution

  • Quick answer, for a quick question.

    1) Use JTextPane.inserComponent or JTextPane.insertIcon to insert your images.

    2) Use a StyledEditorKit to append your styled text. Remember that you can also use an HTMLDocument and HTMLEditorKit to handle html content.