Tutorial 2: Converters



Support This Project


stats counter


Logo SourceForge.net Logo IntelliJ IDEA


In the previous tutorial, one set up a simple menu loader that only takes String as attribute values. What if one likes to add the ability to setup icons, accelerator keys? For example:

<?xml version="1.0"?>
	<menu text="File">
		<menu text="Open">
			<menuitem text="XML"/>
			<menuitem text="Java"/>
		<menuitem text="Exit" accelerator="control Q"/>
	<menu text="Edit">
		<menuitem text="Cut"/>
		<menuitem text="Copy"/>
		<menuitem text="Paste"/>
	<menu text="Help">
		<menuitem text="About" accelerator="F1"/>

There are two major methods dealing with non-string attributes.

  • Write a specific setter for the attribute in concern, usually used for constant values.
  • Still use the DefaultSetter, but write a converter to convert the String literal to the appropriate class object, limited to unique object types.

There are gray areas where both can be used. In those cases, I personally favor converters since they may help setting attributes for other tags as well.

Step 1: Writing a KeyStroke Converter

A converter is quite simple. The string value is the one to be converted into the appropriate object type. The decodeEngine parameter can be useful in retrieving the current CookXml settings as well as getting the current decoding progress.

In general, exceptions generated will be automatically wrapped and handled by CookXml's DecodeEngine, so it is not that necessary to explicitly deal with runtime exceptions.

import javax.swing.*;
import cookxml.core.DecodeEngine;
import cookxml.core.interfaces.Converter;
import cookxml.core.exception.ConverterException;

public class KeyStrokeConverter implements Converter
	public Object convert (String value, DecodeEngine decodeEngine) throws ConverterException
		return KeyStroke.getKeyStroke (value);

Step 2: Installing the Converter

Once the converter is installed into the tagLibrary, it is called by the DefaultSetter whenever a KeyStroke type of attribute is encountered.

tagLibrary.setConverter (KeyStroke.class, new KeyStrokeConverter ());


(c) Copyright 2004-2007 Heng Yuan. All rights reserved.

Valid XHTML 1.0! Valid CSS!