2012-11-15 9 views
1

我必須在JComboBox的下拉列表中設置自定義圖像。我很成功地刪除它(通過重寫getWidth()),但我無法用我的自定義圖像替換箭頭。這是我的代碼片段,以獲得更好的主意。我不知道我在做什麼錯,但它顯示按鈕部分的一些高架部分。在setUI(新BasicComboBOxUI)中重寫setIcon()方法{}

cmbYear = new JComboBox(); 
    cmbYear.setUI(new BasicComboBoxUI(){ 
     protected JButton createArrowButton() { 
      return new JButton() { 
       private static final long serialVersionUID = 1L; 
       public void setIcon(Icon defaultIcon) { 
        defaultIcon = new ImageIcon("images/dropdown_icon.png"); 
        super.setIcon(defaultIcon); 
       } 
    //   public int getWidth() { 
    //    return 0; 
    //   } 
      }; 
     } 
    }); 

請幫我這裏。非常感謝您的時間和建議。

回答

1

您可以改寫getIcon。根據需要緩存圖標。

@Override 
public Icon getIcon() { 
    Icon defaultIcon = new ImageIcon(getClass().getResource("images/dropdown_icon.png")); 
    return defaultIcon; 
} 
+1

非常感謝您的幫助。它的工作完美現在爲以下。 \t圖標defaultIcon = new ImageIcon(「images/dropdown_icon.png」); – Smit

+0

對不起,我從包路徑加載圖標。 –