java - 如何找到 JTextPane 文档的默认属性?

标签 java swing jtextpane

我正在使用 JTextPane。

JTextPane pane = new JTextPane();
String content = "I'm a line of text that will be displayed in the JTextPane";
StyledDocument doc = pane.getStyledDocument();
SimpleAttributeSet aSet = new SimpleAttributeSet();

如果我将此 aSet 添加到文本 Pane 的文档中,如下所示:

doc.setParagraphAttributes(0, content.length(), aSet, false);

没有任何可见的事情发生。这并不奇怪,因为我没有为 aSet 设置任何自定义属性。但是,如果我允许 aSet 替换 doc 的当前 ParagraphAttributes,如下所示:

doc.setParagraphAttributes(0, content.length(), aSet, true);

发生了很多事情。如何获取有关 JTextPane 文档的默认值的信息?特别是我的问题是,当我为 aSet 定义自定义字体并将其设置为替换当前属性时,字体显示为粗体。 StyleConstants.setBold(aSet, false); 没有帮助。

最佳答案

我看过source code查看哪些数据结构保存了您想要的信息。这是对该代码的修改,用于打印每个段落的属性。

int offset, length; //The value of the first 2 parameters in the setParagraphAttributes() call

Element section = doc.getDefaultRootElement();
int index0 = section.getElementIndex(offset);
int index1 = section.getElementIndex(offset + ((length > 0) ? length - 1 : 0));
for (int i = index0; i <= index1; i++)
{
    Element paragraph = section.getElement(i);
    AttributeSet attributeSet = paragraph.getAttributes();
    Enumeration keys = attributeSet.getAttributeNames();
    while (keys.hasMoreElements())
    {
        Object key = keys.nextElement();
        Object attribute = attributeSet.getAttribute(key);
        //System.out.println("key = " + key); //For other AttributeSet classes this line is useful because it shows the actual parameter, like "Bold"
        System.out.println(attribute.getClass());
        System.out.println(attribute);
    }
}

通过 setText() 方法添加一些文本的简单 textPane 的输出给出:

class javax.swing.text.StyleContext$NamedStyle
NamedStyle:default {foreground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],size=12,italic=false,name=default,bold=false,FONT_ATTRIBUTE_KEY=javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=plain,size=12],family=Dialog,}

关于您的特定问题,请查看 related SO question我已经能够将段落文本设置为粗体:

StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aSet = sc.addAttribute(aSet,  StyleConstants.Bold,  true);

在本例中,aSet 的类是 javax.swing.text.StyleContext$SmallAttributeSet,它是不可变的(未实现 MutableAttributeSet )。对于您的情况,大致如下:

aSet.addAttribute(StyleConstants.Bold, true);

应该可以。

关于java - 如何找到 JTextPane 文档的默认属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898802/

相关文章:

由于权限问题,Java 7 ImageIO 在 Windows 7 中可能无法读写

java - 无法构建 apk - android studio

java - Java Swing 中的 EventQueue.invokeLater

java-HotSpot 虚拟机检测到意外错误?解决方案是什么

java - 如何创建一个界面,在左侧显示对象,在右侧显示每个对象的详细信息?

java - 将 JTextPane 的内容保存到普通文本文件失败

java - 无法从TemporalAccessor获取即时消息:{},ISO解析为java.time.format.Parsed类型的2018-01-01

java - 我可以在java中使用什么来代替 'this' 的 addActionListener(this) ?

java - JTextPane高亮多个单词

java - 十六进制编辑器,字节之间的空格