JTextPane String Wrapper

Unlike JTextArea , JTextPane does not have the ability to disable line wrapping. I found one solution to turn off line wrapping in JTextPane s, but for such a simple task it is too much. Is there a better way to do this?

+7
source share
3 answers

See Without Wrap Text Pane . Here the code is included from the link.

 JTextPane textPane = new JTextPane(); JPanel noWrapPanel = new JPanel( new BorderLayout() ); noWrapPanel.add( textPane ); JScrollPane scrollPane = new JScrollPane( noWrapPanel ); 
+10
source
+2
source

No Wrap Text Pane also provides an alternative solution that does not require wrapping a JTextPane in a JPanel ; instead, it overrides getScrollableTracksViewportWidth() . I prefer this solution, but it didn’t work for me at all - I noticed that packaging still occurs if the viewport becomes already the minimum width of the JTextPane .

I found that JEditorPane overrides getPreferredSize() to try to “fix” a situation where the viewport is too narrow, returning the minimum width instead of the preferred width. This can be resolved by overriding getPreferredSize() again to say "no, really, we always want the actual preferred size":

 public class NoWrapJTextPane extends JTextPane { @Override public boolean getScrollableTracksViewportWidth() { // Only track viewport width when the viewport is wider than the preferred width return getUI().getPreferredSize(this).width <= getParent().getSize().width; }; @Override public Dimension getPreferredSize() { // Avoid substituting the minimum width for the preferred width when the viewport is too narrow return getUI().getPreferredSize(this); }; } 
0
source

All Articles