001 // Copyright 2006-2007 Daniel Gredler 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package net.sf.beanform.util; 016 017 import java.util.ArrayList; 018 import java.util.Arrays; 019 import java.util.List; 020 021 import org.apache.hivemind.Messages; 022 import org.apache.tapestry.form.IPropertySelectionModel; 023 024 /** 025 * A generic {@link IPropertySelectionModel} implementation for enumerations. 026 * 027 * @author Daniel Gredler 028 */ 029 public class EnumPropertySelectionModel<T extends Enum<T>> implements IPropertySelectionModel { 030 031 private List<T> values; 032 private List<String> labels; 033 034 public EnumPropertySelectionModel( Class<T> type, boolean includeEmptyOption, Messages messages ) { 035 036 this.values = new ArrayList<T>(); 037 if( includeEmptyOption ) this.values.add( null ); 038 T[] enums = type.getEnumConstants(); 039 this.values.addAll( Arrays.asList( enums ) ); 040 041 this.labels = new ArrayList<String>( this.values.size() ); 042 for( T value : this.values ) { 043 if( value == null ) this.labels.add( "" ); 044 else this.labels.add( messages.getMessage( value.toString() ) ); 045 } 046 } 047 048 public int getOptionCount() { 049 return this.values.size(); 050 } 051 052 public Object getOption( int index ) { 053 return this.values.get( index ); 054 } 055 056 public String getLabel( int index ) { 057 return this.labels.get( index ); 058 } 059 060 public String getValue( int index ) { 061 return Integer.toString( index ); 062 } 063 064 public Object translateValue( String value ) { 065 return this.values.get( Integer.parseInt( value ) ); 066 } 067 068 public boolean isDisabled(int index) { 069 return false; 070 } 071 072 }