Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Enumeration Values In A List Field

Enumeration Values In A List Field

Java Programming Tricks

Enumeration values in a List field:

 Suppose you want the user to choose a color from one of the predefined 
 Java colors, 
 
 Color.red 
 
 Color.yellow 
 
 The traditional solution is tedious: 
 
 1. Add strings to a list field 
 
 2. When a string was selected, use an if/else/else branch to convert it
 to the enum Value. 
 
 if (selection.equals("red")) color = Color.red; 
 
 else if (selection.equals("yellow")) color = Color.yellow; 
 
 else . . .
 
 3. Feel bad for not having set up a hash table instead. 
 
 The problem is that color. red is the name of a constant, whereas "red" 
 is a string object. 
 
 Previous Next 
 
  
 
 Tip 
 
 Use reflection to convert the strings! 
 
 Sample usage: 
 
 new EnumList(Color.class, new String[] {"red", "yellow", . . .}) 
 
 The code: 
 
 class EnumList extends JList 
 
 { public EnumList(Class cl, String[] labels) 
 
 {for (int i = 0; i < Labels.length; i++) 
 
 {    String label = labels[i]; 
 
 int value = 0; 
 
 try 
 
 {   java.lang.reflect.Field f = cl.getField(label); 
 
     value = f.getInt(cl); 
 
 }
 
 catch(Exception e) 
 
 {   Label = "(" + label + ")"; 
 
 } 
 
 table.put (label, new Integer (value i )); 
 
 } 
 
 setListData(labels); 
 
 setSelectedIndex(0); 
 
 }
 
 public int getValue() 
 
 { return ((Integer)table.get(getSelectedValue())).intValue();
 
 }
 
     private Hashtable table = new Hashtable(); 
 
 }
 
 Note 
 
 The drawback of this trick is that it does not work for internationalization. 
 The enumerated constants are usually in English, but your users may want to 
 see them in the local language, i.e. rot gelb
 
 

Partners