假如我要在JComboBox內 Binding SelectedItem, 但顯示的不是Binding的值, 而是對應Binding後的另一個值, 則必需使用Renderer, 並且設定JComboBox的Editable為false才行。如下的example
cbCountry.setRenderer(new CountryListCellRenderer(ct1));
public class CountryListCellRenderer extends JTable implements ListCellRenderer {
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
// 產生combo box中顯示的table
if (value != null) {
setModel(new RowTableModel( Country.findName((String) value), (String) value));
}
if (isSelected) {
getSelectionModel().setSelectionInterval(0, 0);
}
// 控制選取後只顯示code不顯示descrption, 當JComboBox的Editable設為false時, 才會執行這段程式
if (-1 == index && value != null) {
return new JLabel(Country.findName((String) value));
}
// 初始時不顯示任何資料
if (-1 == index && value == null) {
return new JLabel(“");
}
//this.setPreferredSize(new Dimension(200,20));
return this;
}
}