2013-02-22 23 views
1

早上好,請,你能介意幫我確定爲什麼這ListCellRenderer類不設置在組合框單元的圖像圖標: 這裏的ListCellRenderer類:的JComboBox文字和ImageIcon的

class MyComboRendere implements ListCellRenderer { 

    public Component getListCellRendererComponent(JList list, Object value, 
      int index, boolean isSelected, boolean cellHasFocus) { 

     JLabel label = new JLabel(); 
     label.setOpaque(true); 
     label.setText(value.toString()); 
     label.setIcon(new ImageIcon("/pics/Color-icon.png")); 
     if (isSelected) 
      if (index == 0) 
       label.setBackground(Color.RED); 
      else if (index == 1) 
       label.setBackground(Color.GREEN); 
      else 
       label.setBackground(Color.BLUE); 
     return label; 
    } 

} 

,這是一個方法來設置組合框:

public void setComboColor(){ 
    Vector<String> colors=new Vector<>(); 
    comboPanel=new JPanel(new BorderLayout()); 
    colors.add("RED"); 
    colors.add("GREEN"); 
    colors.add("BLUE"); 
    colorCombo=new JComboBox(colors); 
    colorCombo.setRenderer(new MyComboRendere()); 
    comboPanel.add(colorCombo,BorderLayout.BEFORE_FIRST_LINE); 
} 
+0

重耦合,在現實生活中沒有這樣做。不要爲此使用'索引'... – Mordechai 2013-02-22 09:28:26

回答

2

似乎label.setIcon(new ImageIcon("/pics/Color-icon.png"));沒有得到圖標的實際路徑,因爲它總是返回null,但它不會引發異常。於是,我就用這個:

java.net.URL imgURL = getClass().getResource("/pics/Color-icon.png"); 
label.setIcon(icon); 

和它工作正常

1
"/pics/Color-icon.png" 

這是否存在? ImageIcon如果無法加載圖像,則不會拋出任何異常,但會返回null

+0

它不爲空我跟蹤它 – 2013-02-22 09:36:54

1
  1. 不提供FileIO專注裏面XxxRenderer,加載所有圖標給局部變量,測試空值

  2. XxxRenderer發射了大量的事件(鼠標,按鍵和內部的API實現),那麼你飛重建圖標

  3. 閱讀Oracle tutorial about JComboBox,儘量約similair問題的代碼示例

+0

所以你解決了問題的效率,現在呢? – Mordechai 2013-02-22 09:30:58

+0

@ĎMouseEvent現在是什麼?是不是從教程如此接近的代碼.... – mKorbel 2013-02-22 12:46:34