KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > extended > FontConverter


1 package com.thoughtworks.xstream.converters.extended;
2
3 import com.thoughtworks.xstream.converters.Converter;
4 import com.thoughtworks.xstream.converters.MarshallingContext;
5 import com.thoughtworks.xstream.converters.UnmarshallingContext;
6 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
7 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
8
9 import javax.swing.plaf.FontUIResource JavaDoc;
10 import java.awt.*;
11 import java.util.Map JavaDoc;
12
13 public class FontConverter implements Converter {
14
15     public boolean canConvert(Class JavaDoc type) {
16         // String comparison is used here because Font.class loads the class which in turns instantiates AWT,
17
// which is nasty if you don't want it.
18
return type.getName().equals("java.awt.Font") || type.getName().equals("javax.swing.plaf.FontUIResource");
19     }
20
21     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
22         Font font = (Font) source;
23         Map JavaDoc attributes = font.getAttributes();
24         writer.startNode("attributes"); // <attributes>
25
context.convertAnother(attributes);
26         writer.endNode(); // </attributes>
27
}
28
29     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
30         reader.moveDown(); // into <attributes>
31
Map JavaDoc attributes = (Map JavaDoc) context.convertAnother(null, Map JavaDoc.class);
32         reader.moveUp(); // out of </attributes>
33
Font font = Font.getFont(attributes);
34         if (context.getRequiredType() == FontUIResource JavaDoc.class) {
35             return new FontUIResource JavaDoc(font);
36         } else {
37             return font;
38         }
39     }
40 }
41
Popular Tags