【问题标题】:Could "content" of AttributedString can be saved in file?AttributedString 的“内容”可以保存在文件中吗?
【发布时间】:2009-03-02 12:58:03
【问题描述】:

我正在研究如何“绘画” Graphics2D 上的一些属性文本。

所以,我很感兴趣是否可以保存 某种格式的 AttributedString 的内容?

我知道它可以被 Java 序列化, 但是,我在这里不需要那个解决方案。

另外,如果有人知道一些例子 如何编辑属性字符串?

这里是一些 Java 代码,只是为了了解一下:

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

AttributedString as new AttributedString( "Lorem ipsum dolor sit amet..." );
Font font1 = new Font( "SansSerif" , Font.PLAIN , 20 );
as.addAttribute( TextAttribute.FONT       , font1       );
as.addAttribute( TextAttribute.FOREGROUND , Color.black );
as.addAttribute( TextAttribute.FOREGROUND , Color.blue , 4 , 9 );

AttributedCharacterIterator aci = as.getIterator();
FontRenderContext           frc = g2.getFontRenderContext();
LineBreakMeasurer           lbm = new LineBreakMeasurer( aci , frc );

TextLayout  textLayout = lbm.nextLayout( wrappingWidth );

int x = 50 , y = 50 ;
textLayout.draw( g2 , x , y );

}

感谢任何帮助或建议:)

【问题讨论】:

    标签: java swing graphics


    【解决方案1】:

    显然,最简单的方法是 java 序列化,否则您将需要处理所有可能的文本属性。 如果你想要一个例子,这里是我编写的一个报告生成器,它广泛使用了 AttributedString。希望它会有所帮助: http://www.perry.ch/mo/pureport.zip

    【讨论】:

      【解决方案2】:

      AttributedString 没有文本序列化格式,您必须自己编写。

      AttributedString/AttributedCharacterIterator 是在 Java 1.2 中首次引入的旧 API,并且从未被“加强”以提供良好样式的文本模型。例如,您会注意到它缺少一些明显的东西,例如“length()”方法或实现 Externalizable/Serializable。您可以通过为其获取 AttributedCharacterIterator 来对其进行迭代,但是由于可以存在 AttributedCharacterIterator.Attribute 的自定义子类,因此如果没有本机序列化,您将无法可靠地记录所有内容。

      最好只使用 AttributedString 作为与 InputMethod 或 TextLayout API 对话的中间格式,并以其他方式存储您的样式文本。

      【讨论】:

        猜你喜欢
        • 2021-02-06
        • 2017-01-28
        • 2023-02-08
        • 2013-01-14
        • 1970-01-01
        • 1970-01-01
        • 2017-06-17
        • 1970-01-01
        • 2020-07-10
        相关资源
        最近更新 更多