user90
user90

Reputation: 73

How to set preferred size of JTextPane to its content size?

I have a JPanel with Boxlayout and some JTextPanes and JPanels that will be added to it dynamically. I want to set the preferred size of the JTextPanes to fit their content. I use StyledDocument for my JTextPane. How can I do this?

Edit: When I create a new JTextPane I have its content and it won't change. Here is my code:

public void display(final String text){
    StyleContext sc = new StyleContext();
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
    Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);
    final Style style = sc.addStyle("MainStyle", defaultStyle);
    JTextPane pane = new JTextPane(){
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public Dimension getMinimumSize(){
            return new Dimension(text.length()*5, getContentHeight(text.length()*5,text));
        }
        @Override 
        public Dimension  getMaximumSize(){
            return  new Dimension(430, getContentHeight(text.length()*5,text));
        }
    };
    receive.setStyledDocument(doc);
    receive.setEditable(false);
    receive.setPreferredSize(new Dimension(text.length()*5, getContentHeight(text.length()*5,text)));
    
    try {
        doc.insertString(doc.getLength(),text,style);
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Jpanel.add(pane);
    
}

public int getContentHeight(int i, String content) {
        JEditorPane dummyEditorPane=new JEditorPane();
        dummyEditorPane.setSize(i,Short.MAX_VALUE);
        dummyEditorPane.setText(content);
        return dummyEditorPane.getPreferredSize().height;
    }

The issue is in the getMinimumSize(), getMaximumSize(), and setPreferredSize() methods! Also in the width that I set for dummyEditorPane.setSize(i,Short.MAX_VALUE); How can I set a fixed size for the JTextPane?

Upvotes: 1

Views: 1663

Answers (2)

StanislavL
StanislavL

Reputation: 57381

Here is a tip how to measure height for fixed width

public static int getContentHeight(String content) {
    JEditorPane dummyEditorPane=new JEditorPane();
    dummyEditorPane.setSize(100,Short.MAX_VALUE);
    dummyEditorPane.setText(content);

    return dummyEditorPane.getPreferredSize().height;
}

int h=getContentHeight("Long text to be measured in the JEditorPane");

Upvotes: 0

Braj
Braj

Reputation: 46841

Add JTextPane inside JScrollPane to fit as per its content. If it doesn't work then override getPreferredSize() to set the preferred size if needed.

 @Override
 public Dimension getPreferredSize() {
     return new Dimension(..., ...);
 }

See Swing Tutorial on How to Use Editor Panes and Text Panes for examples.

Upvotes: 2

Related Questions