java JTextPane 换行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7156038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JTextPane line wrapping
提问by Jeffrey
Unlike JTextArea
, JTextPane
has no option to turn line wrapping off. I found one solutionto turning off line wrapping in JTextPane
s, but it seems too verbose for such a simple problem. Is there a better way to do this?
与 不同JTextArea
,JTextPane
没有关闭换行的选项。我找到了一种在s 中关闭换行的解决方案JTextPane
,但对于这样一个简单的问题来说似乎太冗长了。有一个更好的方法吗?
回答by camickr
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 );
回答by Kevin K
The No Wrap Text Panealso 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
.
在不换行文本窗格还提供了不需要包裹的替代解决方案JTextPane
中JPanel
,而不是将其覆盖getScrollableTracksViewportWidth()
。我更喜欢那个解决方案,但它对我来说不太奏效 - 我注意到如果视口变得比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':
我发现当视口太窄时,通过返回最小宽度而不是首选宽度来尝试“修复”事物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);
};
}