【问题标题】:Appending richtext to JTextPane using StyledDocument.insertString doesn't preserve fonts使用 StyledDocument.insertString 将富文本附加到 JTextPane 不会保留字体
【发布时间】:2012-07-11 00:09:21
【问题描述】:

我不知道我正在尝试做的事情是否可行。

我有控制台,我想在其中附加这样声明的格式化文本:

private final JTextPane statusText = new JTextPane();

我得到了对其样式文档的引用,如下所示:

private StyledDocument statusDocument = statusText.getStyledDocument();

我定义了一些属性:

private final SimpleAttributeSet gray;
private final SimpleAttributeSet black;
private final SimpleAttributeSet red;

还有一个辅助方法:

private void appendStatusText(String text, SimpleAttributeSet attribute) {
        final String finalText = text;
        final SimpleAttributeSet finalAttribute = attribute;
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    statusDocument.insertString(statusDocument.getLength(), finalText, finalAttribute);
                } catch (BadLocationException e) {
                    log.error("Cannot add " + finalText, e);
                }
            }
        });
    }

我想将 appendStatusText 与属性之一(灰色、红色、黑色)和一些文本一起使用,但它显示的都是灰色,我期待多色。

请帮忙。

PS:我从问题here得到代码

【问题讨论】:

  • 可能是/是否还有其他问题,请使用SSCCE编辑您的帖子
  • @mKorbel 好的,我会尝试准备一个 SSCCE,但首先,您能否确认可以将不同的 SimpleAttributeSet 实例与添加到 JTextPane 的部分文本混合和匹配?跨度>
  • 不,我认为没有问题,另一个问题不是问题,不知何故从(@camickr's)描述中不清楚),你可以(pretty to) use one of those two codes for your SSCCE
  • 看起来错误在其他地方,我使用了您建议的 SSCCE,并对其进行了修改,现在它的行为符合我的预期。我会继续调查,谢谢
  • 问题在于文本面板已将 setEnabled 设置为 false,这导致所有内容都显示为灰色...

标签: java swing jtextpane


【解决方案1】:

TextComponentDemoinitDocument() 方法显示了一种构建此类文档的方法。 example 出现在教程文章How to Use Editor Panes and Text Panes 中的Examples That Use Text Panes and Editor Panes 中。

【讨论】:

    【解决方案2】:

    您必须定义您的 SimpleAttributeSet,然后添加所需的属性,如下所示:

    private SimpleAttributeSet red = new SimpleAttributeSet();      
    red.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.red);
    

    【讨论】:

      猜你喜欢
      • 2019-10-25
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 2022-09-02
      相关资源
      最近更新 更多