Class ObjectToStringConverter

java.lang.Object
org.jdesktop.swingx.autocomplete.ObjectToStringConverter
Direct Known Subclasses:
ObjectToStringConverter.DefaultObjectToStringConverter

public abstract class ObjectToStringConverter extends Object

This class is used to provide string representations for objects when doing automatic completion.

A class inherited from this class could be used, when the object's toString method is not appropriate for automatic completion.

An example for i18n:

public class I18NStringConverter extends ObjectToStringConverter {
  ResourceBundle bundle;

  public I18NStringConverter(ResourceBundle bundle) {
    this.bundle = bundle;
  }

  public String getPreferredStringForItem(Object item) {
    return item==null ? null : bundle.getString(item.toString());
  }
}

It's also possible to return more than one string representation. The following example shows a converter that will allow a user to choose an airport using either the airport's full description (toString()) or its ICAO/IATA code:

public class AirportConverter extends ObjectToStringConverter {

  public String[] getPossibleStringsForItem(Object item) {
    if (item==null) return new String[0];
    if (!(item instanceof Airport)) throw new IllegalArgumentException();
    Airport airport = (Airport) item;
    return new String[]{airport.toString(), airport.icaoCode, airport.iataCode};
  }
      
  public String getPreferredStringForItem(Object item) {
    return item==null?null:getPossibleStringsForItem(item)[0];
  }
}

  • Field Details

    • DEFAULT_IMPLEMENTATION

      public static final ObjectToStringConverter DEFAULT_IMPLEMENTATION
      This field contains the default implementation, that returns item.toString() for any item !=null. For any item ==null, it returns null as well.
  • Constructor Details

    • ObjectToStringConverter

      public ObjectToStringConverter()
  • Method Details

    • getPossibleStringsForItem

      public String[] getPossibleStringsForItem(Object item)
      Returns all possible String representations for a given item. The default implementation wraps the method getPreferredStringForItem. It returns an empty array, if the wrapped method returns null. Otherwise it returns a one dimensional array containing the wrapped method's return value.
      Parameters:
      item - the item to convert
      Returns:
      possible String representation for the given item.
    • getPreferredStringForItem

      public abstract String getPreferredStringForItem(Object item)
      Returns the preferred String representations for a given item.
      Parameters:
      item - the item to convert
      Returns:
      the preferred String representation for the given item.