Search code examples
javaswingjscrollpanejtextpane

Dynamically added content doesn't scroll correctly (JTextPane inside JScrollPane)


The following behavior of JScrollPane(JTextPane) seems to be above my paygrade:

I have added a textPane inside a scrollPane to my frame.

    textPane = new JTextPane();
    scrollPane = new JScrollPane(textPane);

If I set the content of the textPane via textPane.setText("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"), textPane is expanding and scrollPane is doing its job correctly.

enter image description here

However, if I use textPane to redirect out and err using MessageConsole, it does some sort of word-wrap. I check the source of MessageConsole and it does not alter any word-wrap behavior of textPane. It appears that textPane.getDocument().insertString(.) causes textPane to not expand properly.

    MessageConsole mc = new MessageConsole(textPane);
    mc.redirectOut();
    mc.redirectErr(Color.RED, null);
    mc.setMessageLines(100);

enter image description here

How can I avoid that automatic line-break from happening, when feeding content via textPane.getDocument().insertString(.)? I have been unsuccessfully trying to remove this line-break for more than 3 hours now and would really appreciate your help here.


Solution

  • In the first case, when you add a long string of text with no spaces, there is no place for the text to be split to a new line so it appears that the preferred width becomes the width of the long line of text.

    There is no need for the text on all the other lines to wrap since they fit in the preferred width.

    However, in the second case, there are spaces so the default behaviour of the text pane is to wrap text once the viewport is full.

    This wrapping is caused by the default implementation of the Scrollable interface for the JTextPane. The default implementation of the getScrollableTracksViewportWidth() method returns true, which basically attempts to fit all the text in the width of the viewport, causing it to wrap when possible.

    If you don't want the text to wrap then check out No Wrap Text Pane. It shows how you can change the default Scrollable behaviour of the text pane by having the getScrollableTracksViewportWidth() method return false.