I have a JComboBox which displays items which are not Strings, although they do have a toString() method and can be displayed as Strings.
I declare it as:
public class AddressCombo extends JComboBox<Address> {
public AddressCombo(ComboBoxModel<Address> model) {
super(model);
setEditable(true);
}
public AddressCombo(Address... addresses) {
this(new DefaultComboBoxModel<Address>(addresses));
}
// Other stuff snipped
}
This works fine when the JComboBox is not editable, but If I make it editable then the selected item becomes a java.lang.String when edited which is not what we want! In addition the String might not represent a valid value at all (we have a parser that can detect this).
What is the best way to set up a JComboBox so that:
- It manages items of a custom (POJO) type
- It is editable
- When the user edits the field, the user's input can be parsed with a custom parser to see if it is the correct type
- If the input doesn't parse, it can either be corrected or a default value used
- The selected item will therefore always be of the correct class, not a Java
String
I found that the following solution worked:
java.text.Formatto encapsulate the formatting / parsing codeBasicComboBoxEditorto use the formatter with aJFormattedTextFieldJComboBoxsublass to use the aboveCode for those interested: