View Javadoc

1   // Copyright 2006 Daniel Gredler
2   //
3   // Licensed under the Apache License, Version 2.0 (the "License");
4   // you may not use this file except in compliance with the License.
5   // You may obtain a copy of the License at
6   //
7   //     http://www.apache.org/licenses/LICENSE-2.0
8   //
9   // Unless required by applicable law or agreed to in writing, software
10  // distributed under the License is distributed on an "AS IS" BASIS,
11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  // See the License for the specific language governing permissions and
13  // limitations under the License.
14  
15  package net.sf.beanform.util;
16  
17  import java.util.ArrayList;
18  import java.util.Arrays;
19  import java.util.List;
20  
21  import org.apache.hivemind.Messages;
22  import org.apache.tapestry.form.IPropertySelectionModel;
23  
24  /***
25   * A generic {@link IPropertySelectionModel} implementation for enumerations.
26   *
27   * @author Daniel Gredler
28   */
29  public class EnumPropertySelectionModel<T extends Enum<T>> implements IPropertySelectionModel {
30  
31      private List<T> values;
32      private List<String> labels;
33  
34      public EnumPropertySelectionModel( Class<T> type, boolean includeEmptyOption, Messages messages ) {
35  
36          this.values = new ArrayList<T>();
37          if( includeEmptyOption ) this.values.add( null );
38          T[] enums = type.getEnumConstants();
39          this.values.addAll( Arrays.asList( enums ) );
40  
41          this.labels = new ArrayList<String>( this.values.size() );
42          for( T value : this.values ) {
43              if( value == null ) this.labels.add( "" );
44              else this.labels.add( messages.getMessage( value.toString() ) );
45          }
46      }
47  
48      public int getOptionCount() {
49          return this.values.size();
50      }
51  
52      public Object getOption( int index ) {
53          return this.values.get( index );
54      }
55  
56      public String getLabel( int index ) {
57          return this.labels.get( index );
58      }
59  
60      public String getValue( int index ) {
61          return Integer.toString( index );
62      }
63  
64      public Object translateValue( String value ) {
65          return this.values.get( Integer.parseInt( value ) );
66      }
67  
68  }