Search code examples
javahtmljscrollpanejtextpane

JtextPane with HTML is too wide


I am trying to create a scrollable JTextPane to display HTML. I have it working with the exception of trying to get the size right. It seems no matter what I do, I cannot effect the width of the pane.

JTextPane tp=new JTextPane();
        tp.setSize(300,300);
        tp.setContentType("text/html");
        HTMLDocument html=(HTMLDocument) tp.getDocument();
        html.putProperty("IgnoreCharsetDirective", new Boolean(true));
        HTMLEditorKit htmle=(HTMLEditorKit) tp.getEditorKit();
        try {
            htmle.insertHTML(html,html.getLength(),content,0,0,null);
        } catch (BadLocationException | IOException e) {
            // Should not get here
            e.printStackTrace();
        }
        JScrollPane scroll=new JScrollPane(tp,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setSize(200,300);
        JOptionPane.showMessageDialog(null,scroll,title,JOptionPane.INFORMATION_MESSAGE);

I've tried setsize on the JTextPane and the JScrollPane but neither effects the width. It seems that it wants set the width to that of the longest < p > tag rather than wrap the HTML within the specified size. What I can't seem to find is a way to set the size of the JOptionPane but my understanding is that should not be necessary if the components are sized correctly. Can someone tell me what I am missing? TIA.


Solution

  • JOptionPane calls pack(). And pack() uses the preferredSize of its children to decide of its width and height. By default, the preferred width of a JTextPane is the width of the longest line. If you want to change this behaviour,

    • Or override the getPreferredSize method of the JTextPane
    • Or use setPreferredSize on your JTextPane instead of setSize