2012-01-29 48 views
1

我想知道如何更改我的JComboBox中的商品列表的名稱?這是我的代碼 我想將其更改爲Dog,Panda,Bee。而不是選擇他們的路徑。JComboBox商品列表

import java.awt.FlowLayout; 
import java.awt.event.ItemEvent; 
import java.awt.event.ItemListener; 
import javax.swing.JFrame; 
import javax.swing.ImageIcon; 
import javax.swing.Icon; 
import javax.swing.JLabel; 
import javax.swing.JComboBox; 

public class ComboTest { 

    private JLabel imageLabel; 
    private JComboBox comboImage; 

    private String[] names = {"images/dog.gif","images/bee.gif","images/Panda.gif"}; 
    private Icon[] icons = { 
     new ImageIcon(getClass().getResource(names[0])), 
     new ImageIcon(getClass().getResource(names[1])), 
     new ImageIcon(getClass().getResource(names[2])), 
    }; 

    public ComboTest(){ 
     initComponents(); 
    } 

    public void initComponents(){ 
     JFrame frame = new JFrame("Test Combo"); 
     frame.setVisible(true); 
     frame.setSize(320, 160); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new FlowLayout()); 

     comboImage = new JComboBox(names); 
     comboImage.addItemListener(new ItemListener(){ 
      public void itemStateChanged(ItemEvent event){ 
       if(event.getStateChange() == ItemEvent.SELECTED){ 
        imageLabel.setIcon(icons[comboImage.getSelectedIndex()]); 
       } 
      } 
     }); 

     frame.add(comboImage); 
     imageLabel = new JLabel(icons[0]); 
     frame.add(imageLabel); 
    } 
} 
+3

爲什麼-o-爲什麼他們不再讀:http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html – kleopatra 2012-01-29 14:36:15

+0

這個功課? – 2012-01-29 14:37:39

+0

由於我不知道你的目標是什麼,爲什麼你不能聲明姓名= {「狗」,「蜜蜂」,「熊貓」}; ? 所以你的問題是如何將「Dog」關聯到「images/dog.gif」我是否正確? – thermz 2012-01-29 14:41:07

回答

2

您可能想要創建一個具有兩個屬性的對象,即要顯示的路徑和文本。

然後,您將設置toString方法返回文本屬性。免責聲明:我還沒有測試任何此代碼。

public class ValueText { 
    private String text; 
    private String value; 

    public ValueText(final String text, final String value) { 
     this.text = text; 
     this.value = value; 
    } 

    @Override 
    public String toString() { 
     return text; 
    } 

    public String getValue() { 
     return value; 
    } 
} 

然後你就可以在你的初始陣列更改爲類似:

private Object[] names = { 
    new ValueText("Dog", "images/dog.gif"), 
    new ValueText("Bee", "images/bee.gif"), 
    new ValueText("Panda", "images/Panda.gif") 
}; 

,它應該工作類似,只是現在,當你正在檢查所選擇的項目,你可以使用getValue()方法獲取路徑。

您可能也有興趣在一個自定義渲染,但它可能沒有必要爲您的使用:克列奧帕特拉後的意見做了一些令人信服的論據 http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

更新我會繼續和改正,你應該在下面閱讀。

這樣做的更通用和更乾淨的方法是使用自定義渲染器,即使它非常簡單(請參閱上面的鏈接)。

+0

感謝您的努力,但是您不認爲這對於簡單操作來說是相當長的嗎? – user962206 2012-01-29 14:49:00

+0

@ user962206:一個更簡單的方法是使用HashMap ,但是說Wes的推薦是相當有效的,雖然你當前的情況可能是一個簡單的例子,但他的方法可以應用於更復雜的例子後來。我建議你按照他的建議1+加票。 – 2012-01-29 14:53:43

+0

-1包裝類和覆蓋它的toString不是推薦的方式 - 自定義渲染器是你需要的 – kleopatra 2012-01-29 14:58:10