AttributeSet构造

时间:2017-11-19 00:47:25

标签: java swing

我正在尝试使用javadoc来构造SimpleAttributeSet https://docs.oracle.com/javase/7/docs/api/javax/swing/text/SimpleAttributeSet.html

构造

SimpleAttributeSet(AttributeSet source)

根据提供的属性集创建新的属性集。

所以我需要构建一个属性集来放入该构造函数。看看那个javadoc 在https://docs.oracle.com/javase/7/docs/api/javax/swing/text/AttributeSet.html 没有构造函数。提供的所有方法都返回有关属性集的一些信息,但没有任何构造它或改变它。

所以问题是,如何构造AttributeSet(然后是SimpleAttributeSet)?

目标是定义一些字体用于StyledDocuments,并将定义字体的所有代码移动到一个单独的类中,以便使用它们的代码更具可读性。

在字体类中:

SimpleAttributeSet myFont = new SimpleAttributeSet(myAttributeSet)
目标类

doc.insertString(doc.getLength(),"myText",myFont);

编辑添加:
目标就像是

    public SimpleAttributeSet newFont = new SimpleAttributeSet(
      StyleConstants.setFontFamily("SansSerif"),
      StyleConstants.setFontSize(16)
      );

1 个答案:

答案 0 :(得分:1)

  

目标是定义一些字体用于StyledDocuments,并将定义字体的所有代码移动到一个单独的类中,以便使用它们的代码更具可读性。

可能是这样的:

public static class DocumentAttributes
{
    private static SimpleAttributeSet font;
    private static SimpleAttributeSet boldFont;

    public static SimpleAttributeSet getFont()
    {
        if (font != null)
            return font;

        font = new SimpleAttributeSet()    
        StyleConstants.setFontFamily(font, "SansSerif");
        StyleConstants.setFontSize(font, 16);

        return font;
    }

    public static SimpleAttributeSet getBoldFont()
    {
        if (boldFont != null)
            return boldFont;

        boldfont = new SimpleAttributeSet( getFont() );    
        StyleConstants.setBold(boldFont, true);

        return boldFont;
    }

}

然后你就可以使用它:

doc.insertString(doc.getLength(),"myText", DocumentAttributes.getFont());