Java Swing How to - Fill Human Readable Value from Enum to JComboBox








Question

We would like to know how to fill Human Readable Value from Enum to JComboBox.

Answer

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
/*www  .  j  a v  a 2s .  com*/
public class Main {
   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;
   }
}