【问题标题】:Set body width for StyledDocument (JTextPane)为 StyledDocument (JTextPane) 设置正文宽度
【发布时间】:2015-05-08 17:13:27
【问题描述】:

我可以这样做,我的富文本将具有固定宽度

JTextPane pane = new JTextPane();
pane.setContentType("text/html");
pane.setText("<html><body style='width:100px'>Some text</body></html>"); 

但我直接使用 Document,没有 HTML。如何设置宽度?

DefaultStyledDocument doc = (DefaultStyledDocument) pane.getStyledDocument();
//??? (set width)

【问题讨论】:

  • 我觉得不可能,试试setMinimumSizepane吧。
  • 为什么不设置组件的大小而不是通过文档来设置?

标签: java swing jtextpane


【解决方案1】:

宽度不是模型(文档)的一部分。应该有一个 View 来处理 Document 的 width 属性并相应地设置宽度。

您应该替换 EditorKit 的 ViewFactory 中的根视图 (SectionView) 以返回宽度取自 Document 元素的自定义视图。

例如查看链接 http://java-sl.com/Pagination_In_JEditorPane.html

它描述了如何向 EditorKit 添加分页。您可以使用代码作为示例并仅修复宽度。

Extend EditorKit.
Replace default ViewFactory with yours
Replace root view (SectionView)
Replace the view's getPreferredSpan(int axis) for X axis to use the width from the Document

【讨论】:

    【解决方案2】:

    除了 Document 是 StyledDocument 之外,它也只有两个级别:段落和字符。在这种情况下,可以使用 HTMLDocument 并使用 CSS 样式表 (body { width: 14cm; }) 构建它,或者适当地更改 CSS 样式表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 2016-08-13
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多