01 Apr 2002

Mon, 01 Apr 2002

Java Font Tricks

Of all the cool things that you can do with Electric's XML Parser, here's a useful one. This code will allow you to define your own font attributes for any swing program on an application-wide basis. The font characteristics are specified in XML so that they can be changed at runtime without recompiling. Neat, and barely 15 lines of code - thanks to the Mind Electric.


Here's the java source:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import java.io.File;
import electric.xml.*;


public class  TestFonts
{
 public static void main(String[] args) throws Exception
 {
        parseXmlFontProperties();


        // YOUR SWING CODE GOES HERE
 }


    private static void parseXmlFontProperties() throws Exception
    {
        Document document = new Document( new File( "fonts.xml" ) );
        Element root = document.getRoot();
        Elements elements = root.getElements( "component" );
        while( elements.hasMoreElements() )
        {
            Element element = elements.next();
            String component = element.getAttributeObject("name").getValue();
            String font = element.getTextString("font");
            int embellishment = element.getInt("embellishment");
            int size = element.getInt("size");
            UIManager.put(component, new FontUIResource(font, embellishment, size));
        }
    }


}


Here's the XML config file (fonts.xml):


<fontspec>
  <component name='Button.font'>
   <font>SansSerif</font>
   <embellishment>0</embellishment>
   <size>24</size>
  </component>
  <component name='TextField.font'>
   <font>SansSerif</font>
   <embellishment>0</embellishment>
   <size>12</size>
  </component>
</fontspec>

Posted at: 17:24 | permalink