JTextPane line wrapping

安稳与你 提交于 2019-12-17 19:41:07

问题


Unlike JTextArea, JTextPane has no option to turn line wrapping off. I found one solution to turning off line wrapping in JTextPanes, but it seems too verbose for such a simple problem. Is there a better way to do this?


回答1:


See No Wrap Text Pane. Here's the code included from the link.

JTextPane textPane = new JTextPane();
JPanel noWrapPanel = new JPanel( new BorderLayout() );
noWrapPanel.add( textPane );
JScrollPane scrollPane = new JScrollPane( noWrapPanel );



回答2:


The No Wrap Text Pane also provides an alternative solution that doesn't require wrapping the JTextPane in a JPanel, instead it overrides getScrollableTracksViewportWidth(). I prefer that solution, but it didn't quite work for me - I noticed that wrapping still occurs if the viewport becomes narrower than the minimum width of the JTextPane.

I found that JEditorPane is overriding getPreferredSize() to try and 'fix' things when the viewport is too narrow by 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);
    };
}


来源:https://stackoverflow.com/questions/7156038/jtextpane-line-wrapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!