Wednesday, June 18, 2008

Metawidget and SwingX

Update: the APIs shown in this blog entry have changed slightly in newer releases of Metawidget. Specifically you should now use a WidgetBuilder to add support for third-party components. Please download the latest documentation from http://metawidget.org

There's been a bit of interest in whether Metawidget can use SwingX components instead of standard Swing ones. The answer is yes! Metawidget makes it easy to support third-party component libraries. Here's how:

Step 1: Derive your own SwingXMetawidget

Subclass SwingMetawidget and override its buildActiveWidget method to select SwingX components. For example:

package com.myapp.metawidget.swingx;

import static org.metawidget.inspector.InspectionResultConstants.*;
import java.awt.*;
import javax.swing.JComponent;
import org.jdesktop.swingx.JXDatePicker;
import org.metawidget.util.ClassUtils;

public class SwingXMetawidget extends SwingMetawidget {

   public JComponent buildActiveWidget( Map<String, String> attributes )
      throws Exception {

         String type = attributes.get( TYPE );

         if ( type != null ) {
            Class<?> clazz = ClassUtils.niceForName( type );

            // Use SwingX JXDatePicker
            if ( Date.class.isAssignableFrom( clazz ) )
                  return new JXDatePicker();

      }

      // Not for SwingX
      return super.buildActiveWidget( attributes );
   }

   protected String getValueProperty( Component component ) {
      if ( component instanceof JXDatePicker )
         return "date";


      return super.getValueProperty( component );
   }
}

That's it! You'll get all the other Metawidget benefits (like layouts, internationalization, etc.) for free. Note that overriding getValueProperty is optional, but necessary if you want automatic two-way data binding between the JXDatePicker and your business objects.

Step 2: Use SwingXMetawidget in your Application

To try it, download the Metawidget source and update the Swing Address Book example's ContactDialog to say...

final SwingMetawidget metawidget = new SwingXMetawidget();

...(on about line 135). Run the example, double click on Homer Simpson and you'll see the SwingX JXDatePicker component used for the 'Date of Birth' field (previously it was just a JTextField, because vanilla Swing doesn't have a Date picker):

0 comments: