I want to display single word attributed text in a JScrollPane. So I
have to use a StyledDocument in a JTextPane. But I want to avoid line
wrapping.
In PlainDocument, there is a setLineWrap(boolean), but not in
StyledDocument. So, how to do?
Wolfgang
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 -
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
(This is 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();
super.setBounds(x
,y
,Math.max(size.width, width)
,height
);
}
And also implement an additional method -
public JScrollPane createJScrollPane() {
return new JScrollPane(this, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
This encapsulates the special JScrollPane creation.
-sandip
Wolfgang
Sandip Chitale schrieb: