Skip to end of metadata
Go to start of metadata

A component formatter is an implementation of the interface ComponentFormatter that creates a String representation of a GUI component. FEST-Swing provides default component formatters for all the Swing components in the JDK. Unlike the toString method in Swing components, the provided component formatters display only the information that can help developers solve problems in functional tests, excluding any information related to the appearance of GUI components (e.g. colors, layouts, sizes, etc.)

The following are some examples of the output of the some of the provided component formatters.

org.fest.swing.test.TestFrame[name='frame', title='FormattingTest', enabled=true, showing=true]

javax.swing.JButton[name='button', text='A button', enabled=false]

javax.swing.JList[name='list', selectedValues=['One', 2], contents=['One', 2, 'Three', 4], selectionMode=MULTIPLE_INTERVAL_SELECTION, enabled=true]

javax.swing.JOptionPane[message='A message', messageType=ERROR_MESSAGE, optionType=DEFAULT_OPTION, enabled=true, showing=false]

javax.swing.JTabbedPane[name='tabbedPane', selectedTabIndex=1, selectedTabTitle='Second', tabCount=2, tabTitles=['First', 'Second'], enabled=true]:

Custom Component Formatters

There might be cases that you might want to create your own custom formatter to override an existing one or to add support for custom GUI components.

Implement the ComponentFormatter interface

The interface ComponentFormatter provides two methods:

  1. Class<? extends Component> targetType(): Returns the type of component this formatter supports. For example, by returning JButton.class a formatter indicates that it supports instances of JButton and subclasses of JButton.
  2. String format(Component c): Returns the String representation of the given GUI component.
Configure an IntrospectionComponentFormatter

The easiest way to create a component formatter is to configure an instance of IntrospectionComponentFormatter, which, as the name suggests, uses introspection to display property values of a GUI component.

The following code listing shows how to configure a IntrospectionComponentFormatter to support JLabels (and subclasses) and the properties to show:

Register your custom formatter

After creating a custom formatter, we need to register it with FEST-Swing. It is very simple, we only need to call the static method register in org.fest.swing.format.Formatting:

FEST-Swing uses the formatter that supports the type that is the closest to the type of the given GUI component. For example, if we have 'formatter1', a formatter registered to format instances of JButton, and 'formatter2', a formatter registered to format instances of MyOwnButton (a subclass of JButton,) FEST-Swing will use 'formatter2' to format instances of MyOwnButton.