Question

Is there a way to pull information from a field of an Enum and display it in a JComboBox instead of the name? I apologize in advance if my question is ambiguous or unclear.

Here is an abridged version of the enum I'm using:

 public enum Country {

    AF("af", "Afghanistan"),

    ...

    ZW("zw", "Zimbabwe");

    private String nameCode;

    private String displayName;

    private Country(String code, String name) {
        this.nameCode = code;
        this.displayName = name;
    }

    public String getNameCode() {
        return this.nameCode;
    }

    public String getDisplayName() {
        return this.displayName;
    }

    @Override
    public String toString() {
        return this.displayName;
    }

}

I'm using it in the following JComboBox:

JComboBox<Country> boxCountry = new JComboBox<>();
boxCountry.setModel(new DefaultComboBoxModel<>(Country.values()));
inputPanel.add(boxCountry);

However, the combo box displays the name of the Enum value (AF, ZW, etc.). Is there a way to make it display displayName instead? I had thought that maybe overriding the toString method would solve it, but it made no difference. As simple (and common) as this would seem to be, I haven't been able to find anything at all about doing this in Java (I did find an answer on how to do it in C#... too bad I'm not using C#).

Thank you in advance!

Était-ce utile?

La solution

Your question and your code don't match. The JComboBox should show the Country's displayName since that is what your enum's toString() override returns.

And in fact when I test it, that is what I see:

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

public class TestCombo {
   public static void main(String[] args) {
      JComboBox<Country> countryBox = new JComboBox<Country>(Country.values());
      JOptionPane.showMessageDialog(null, new JScrollPane(countryBox));
   }
}

enum Country {

   AF("af", "Afghanistan"),

   US("us", "United States"),

   ZW("zw", "Zimbabwe");

   private String nameCode;

   private String displayName;

   private Country(String code, String name) {
       this.nameCode = code;
       this.displayName = name;
   }

   public String getNameCode() {
       return this.nameCode;
   }

   public String getDisplayName() {
       return this.displayName;
   }

   @Override
   public String toString() {
       return this.displayName;
   }

}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top