JComboBox Item List

↘锁芯ラ 提交于 2019-12-07 16:36:25

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!