我有一個列表,我需要從JComboBox中選擇Customer
對象。從我讀到的,我需要實現一個自定義渲染器,讓我想要顯示在列表中的字段。Java JComboBox自定義渲染器和GTK
我希望我的JComboBox有格式化爲這樣的條目:
+----------------------------------------------+
| Customer Name - Contact - City, State V |
+==============================================+
| Customer #2 Name - Contact - City, State |
| Customer #3 Name - Contact - City, State |
| Customer #4 Name - Contact - City, State |
| Customer #5 Name - Contact - City, State |
+----------------------------------------------+
我用這個代碼:
公共類CustomerListCellRenderer擴展DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Customer) {
Customer c = (Customer) value;
StringBuffer sb = new StringBuffer();
if (c.getCompany() != null && c.getCompany().length() > 0) {
sb.append(c.getCompany());
}
sb.append(" - ");
if (c.getCompany() != null && c.getCompany().length() > 0) {
sb.append(c.getContact());
}
sb.append(" - ");
if (c.getCompany() != null && c.getCompany().length() > 0) {
sb.append(c.getCity());
sb.append(", ");
}
if (c.getCompany() != null && c.getCompany().length() > 0) {
sb.append(c.getState());
}
setText(sb.toString());
}
return this;
}
}
這並不正常工作在Solaris/Unix/Linux下使用系統GTKLookAndFeel。組合框的輸入區域的背景沒有繪製,也沒有繪製邊框。 (見下面的截圖)。是否有另外一種方法可以在三大平臺(Win/Mac/GTK)上正常工作?我可以做一個轉換器來做到這一點,只能操作數據而不是GUI?
我目前的解決方法是覆蓋我的Customer對象上的toString(),以我想要的格式顯示每條記錄,但是尋找其他想法。
alt text http://i40.tinypic.com/5dw1hd.jpg
尼克
我看不出爲什麼你會需要一個自定義渲染器的例子。 – 2009-06-25 18:47:31