JComboBox帶出另一個值

假如我要在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;
}

}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

What is 10 + 4 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)