2012-11-13 18 views
0

我想創建一個包含數據和jCombobox項目的列表。 我用這個listCellRenderer:java jcombobox裏面的一個listCellRenderer

public class DeliveryListCellRenderer extends JPanel implements ListCellRenderer{ 

    JLabel[] lbl = new JLabel[2]; 
    JComboBox combo; 

    public DeliveryListCellRenderer() 
    { 
    setLayout(new GridLayout(0,2,15,0)); 
    lbl[0] = new JLabel("",JLabel.RIGHT); 
    add(lbl[0]); 
    lbl[1] = new JLabel("",JLabel.LEFT); 
    add(lbl[1]); 
    String[] timeZones = {"timeZone 1", "timeZone 2", "timeZone 3", "timeZone 4"}; 

    combo = new JComboBox(timeZones); 
    combo.setSelectedIndex(1); 

    add(combo); 
    } 
    public Component getListCellRendererComponent(JList list,Object value, 
         int index,boolean isSelected,boolean cellHasFocus) 
    { 
    Delivery delivery = (Delivery)value; 
    lbl[0].setText("X : "+delivery.getNode().getX()); 
    lbl[1].setText("Y : "+delivery.getNode().getY()); 
    if(isSelected) setBackground(Color.CYAN); 
    else setBackground(Color.WHITE); 
    return this; 
    } 
} 

當我運行應用程序,一切都顯得正常,但是當我點擊下拉框沒有任何反應。

有沒有人有想法? 在此先感謝。

回答

3

當我運行應用程序時,一切都顯示正常,但沒有任何反應,當我點擊組合框。

0

您需要將內容映射到與對象一起顯示在ComboBox中。

我會建議如下: (T是你的對象的類型)。

public class CustomComboBoxRenderer extends JLabel implements ListCellRenderer<T> { 

    @Override 
    public Component getListCellRendererComponent(JList<? extends T> list, T value, int index, boolean isSelected, boolean cellHasFocus) { 

    if (isSelected) { 
     setBackground(list.getSelectionBackground()); 
     setForeground(list.getSelectionForeground()); 
    } 
    else { 
     setBackground(list.getBackground()); 
     setForeground(list.getForeground()); 
    } 
    if (index == -1) { 
     setOpaque(false); 
     setForeground(list.getForeground()); 
    } 
    else { 
     setOpaque(true); 
    } 
    setFont(list.getFont()); 

    if (value != null) { 
     setText(value.getName()); 
    } 

    return this; 
    } 
} 

組合框創建:

JComboBox<T> comboBox = new JComboBox<T>(); 
    comboBox.setRenderer(new CustomComboBoxRenderer()); 
    add(comboBox); 

希望這有助於。

+1

_your問題來自於透明度管理_這與問題的關係如何:_everything看起來不錯,但是當我點擊combobox_(或者換句話說:這個答案是錯誤的)時什麼也沒有發生 – kleopatra

+0

@kleopatra:thank you for您的反饋。但是,這是我的作品。我同意評論「問題來自透明度管理」並不是最好的,但是下面的代碼部分映射要在數據對象中顯示在組合框中的字符串: \t if(value!= null){ setText(value.getName()); } –

+0

請仔細閱讀該問題(其中明確表示不過分明確,並且它的要求在JList中不受支持,因爲_renderer_不是容器層次結構的一部分)......您的答案完全不相關。 – kleopatra