JTextPane换行

JTextArea不同, JTextPane无法选择关闭换行。 我找到了一个解决 JTextPane的换行问题的解决方案 ,但对于这样一个简单的问题来说它似乎太冗长了。 有一个更好的方法吗?

请参见无包装文本窗格 。 这是链接中包含的代码。

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

希望这有助于http://java-sl.com/wrap.html

No Wrap Text Pane还提供了一种替代解决方案,它不需要在JPanel包装JTextPane ,而是覆盖getScrollableTracksViewportWidth() 。 我更喜欢这个解决方案,但它对我来说并不适用 – 我注意到如果视口变得比JTextPane的最小宽度窄,则仍然会发生包装。

我发现JEditorPane正在重写getPreferredSize()以便在视口太窄时通过返回最小宽度而不是首选宽度来尝试“修复”事物。 这可以通过再次覆盖getPreferredSize()来解决’不,真的 – 我们总是想要实际的首选大小’来解决:

 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); }; }