How can I prevent a JTextPane from word wrapping, and instead, place it in a JScrollPane that will scroll both horizontally and vertically?

Sandip Chitale

Here is a solution -

Swing Scrollable interface is implemented by JComponent. It has a method -

boolean getScrollableTracksViewportWidth()
        Return true if a viewport should always force the
	width of this Scrollable to match the width of the viewport.

The JTextPane happens to return true from this method. What that means is that the containing JScrollPane will always force the width of contained JTextPane to the width of viewport (using setBounds(x,y,w,h)).

The JTextPane automatically wraps the contents if they do not fit in the forced width.

If one wants to disable wrapping in JTextPane one has to override the setBounds(x,y,width, height) method and set the

height = JTextPane.getPreferredSize().height;
width = Math.max(width, JTextPane.getPreferredSize().width);

To enable the scrolling on has to also set the HORIZONTAL SCROLLBAR POLICY of JScrollPane to -


(This is the only caveat, the Horizontal scrollbar appears even when not required).

I usually subclass the JTextPane and override the setBounds like this :

        public void setBounds(int x, int y,int width, int height)
            Dimension size = this.getPreferredSize();
                            ,Math.max(size.width, width)

And also implement an additional method -

public JScrollPane createJScrollPane() {

 return new JScrollPane(this, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

This encapsulates the special JScrollPane creation.