I stumbled upon this question and made some Changes to Duncan's answer. My solution looks like this:
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
public class JEComboBox<T> extends JComboBox<T> {
public JEComboBox(final T placeHolder){
setModel(new DefaultComboBoxModel<T>() {
private static final long serialVersionUID = 1L;
boolean selectionAllowed = true;
@Override
public void setSelectedItem(Object anObject) {
if (!placeHolder.equals(anObject)) {
super.setSelectedItem(anObject);
} else if (selectionAllowed) {
// Allow this just once
selectionAllowed = false;
super.setSelectedItem(anObject);
}
}
});
addItem(placeHolder);
}
}
When adding a place holder you create a anonymous object and overriding the toString method. Implementation could look like this:
public class car{
String final model;
public car(String model){
this.model = model;
}
}
and the creation of the JEComboBox:
JEComboBox comboBoxWithPlaceHolder = new JEComboBox<Car>(new Car{
public String toString(){
return "- Select your car -"
}
});
Pros
Cons
- You need to implement an anonymous subtype of T and Override toString() method and thus wont work on final classes (It can get messy if comboBox hold classes that inherits from a interface, since the anonymous subtype need to implement the interface, thus there will be null returning methods.)