JTextPane adds large spaces every time I insertString

Hi I'm making a chat app and first used a simple JTextPane for a basic color-aware chat view pane. Then I wanted to add support for html links to make them available by adding an HTML listener and setting the content type to text / html. Clickable links work fine, but now every time I insert a String the chat will add a lot of space. Here is the code I am using below:


    public JTextPaneTest() {
    this.addHyperlinkListener(new LinkController());


This is how I add plain text:

    public void append(Color c, String s) {

    SimpleAttributeSet sas = new SimpleAttributeSet(); 

    StyleConstants.setForeground(sas, c);

    StyledDocument doc = (StyledDocument)this.getDocument();

    int len = getDocument().getLength();

    try {
        doc.insertString(len, s, sas);
    } catch (BadLocationException e) {

    setCaretPosition(len + s.length());


And this is how I insert links

    public void addHyperlink(URL url, String text) {
    try {
        Document doc = this.getDocument();
        SimpleAttributeSet hrefAttr = new SimpleAttributeSet();
        hrefAttr.addAttribute(HTML.Attribute.HREF, url.toString());

        SimpleAttributeSet attrs = new SimpleAttributeSet();
        attrs.addAttribute(HTML.Tag.A, hrefAttr);
        StyleConstants.setUnderline(attrs, true);
        StyleConstants.setForeground(attrs, Color.blue);

        doc.insertString(doc.getLength(), text, attrs);
    catch (BadLocationException e) {


For whatever reason, when the content type is set to base text only, I don't get this problem.

Here are some photos: http://i.stack.imgur.com/dpMBB.png

In the picture, the Name is inserted, then :, Then the rest of the text.

Edit: For whatever reason, the JTextPane will automatically center my InsertStrings.

Edit2: Is it possible to remove the margin between inserted lines in HTML? I've tried everything for hours on end and just can't seem to find a solution. The only possible solution I can think of is reformatting the text via getText / setText every time I insert a line to avoid adding fields.


source to share

2 answers

I ended up using only basic "text" and using components to detect clicks.

To fix this problem I was having with HTML, I simply used

editorKit.insertHTML(doc, doc.getLength(), "html code", 0, 0, null);


Instead of inserting my code directly with doc 'insertString'



Instead of inserting the text ith attribute, try creating a dummy element and replace it with outer HTML containing th link

 SimpleAttributeSet a=new SimpleAttributeSet();
 doc.setCharacterAttributes(start, text.length(), a, false);

 Element elem=doc.getCharacterElement(start);
 String html="<a href='"+text+"'>"+text+"</a>";
 doc.setOuterHTML(elem, html);


See a working example here



All Articles