views:

111

answers:

2

I am doing some research on how to "draw" some attributed text on Graphics2D.

So, i am interested is it possible to save content of AttributedString in some format ?

I know it could be Java serialized, but, i don't need that solution here.

Also, if somebody knows some example which shows how to edit AttributedString ?

Here is some Java code, just to get idea:

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 );

}

Thanx for any help or advice :)

+1  A: 

Obviously, the simplest method is java serialization, otherwise you will need to handle all the possible text attributes. If you want an example, here is a report generator that I have written and that make extensive use of AttributedString. Hope it will help: http://www.perry.ch/mo/pureport.zip

Maurice Perry
A: 

There's no text serialization format for AttributedString, you'd have to write your own.

AttributedString/AttributedCharacterIterator is an old API first introduced in Java 1.2 and has never been 'beefed up' to provide a good styled text model. You'll notice for example that it's missing a few obvious things, such as a 'length()' method, or implementing Externalizable/Serializable. You can iterate over it by getting an AttributedCharacterIterator for it, but since a custom subclass of AttributedCharacterIterator.Attribute can be present, you can't reliably record everything without native serialization.

It's better to just use AttributedString as an intermediate format used for talking to the InputMethod or TextLayout APIs, and store your styled text some other way.

dougfelt