如何关闭 JTextPane 换行?
与 JTextArea
不同,JTextPane
没有关闭换行的选项。我找到了一种解决方案来关闭JTextPane
中的换行,但是对于这样一个简单的问题来说似乎太冗长了。有更好的方法吗?
Unlike JTextArea
, JTextPane
has no option to turn line wrapping off. I found one solution to 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅无换行文本窗格。这是链接中包含的代码。
See No Wrap Text Pane. Here's the code included from the link.
无换行文本窗格还提供了另一种选择该解决方案不需要将
JTextPane
包装在JPanel
中,而是重写getScrollableTracksViewportWidth()
。我更喜欢这个解决方案,但它对我来说不太有效 - 我注意到,如果视口变得比JTextPane
的最小宽度更窄,仍然会发生换行。我发现 JEditorPane 正在重写 getPreferredSize() 来尝试通过返回最小宽度而不是首选宽度来“修复”视口太窄的情况。这可以通过再次重写
getPreferredSize()
并说“不,真的 - 我们总是想要实际的首选大小”来解决:The No Wrap Text Pane also provides an alternative solution that doesn't require wrapping the
JTextPane
in aJPanel
, instead it overridesgetScrollableTracksViewportWidth()
. 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 theJTextPane
.I found that
JEditorPane
is overridinggetPreferredSize()
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 overridinggetPreferredSize()
again to say 'no, really - we always want the actual preferred size':