Reputation: 16147
I am wondering how would I change the name of the item list in my JComboBox?here's my code I want to change it to Dog, Panda, bee. rather than choosing their path.
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);
}
}
Upvotes: 1
Views: 2822
Reputation: 33185
You probably want to make an object with two properties, the path and the text you want to display.
Then you'll set the toString
method to return the text property. Disclaimer: I haven't tested any of this code.
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;
}
}
Then you can change your initial array to something like:
private Object[] names = {
new ValueText("Dog", "images/dog.gif"),
new ValueText("Bee", "images/bee.gif"),
new ValueText("Panda", "images/Panda.gif")
};
And it should work similarly, only now, when you are inspecting the selected item, you can use the getValue()
method to get the path.
You also might be interested in a custom renderer, but it's probably not necessary for your use: http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer
Update I'll go ahead and make a correction after kleopatra made some convincing arguments in the comments, which you should read below.
A more general purpose and cleaner way of doing this is with a custom renderer, even if it's very simple (see link above).
Upvotes: 2