org.tentackle.fx.translate.EnumStringTranslator Maven / Gradle / Ivy
/*
* Tentackle - https://tentackle.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.tentackle.fx.translate;
import org.tentackle.fx.FxTextComponent;
import org.tentackle.fx.ValueTranslatorService;
import java.util.function.Function;
/**
* Abstract base class for enum translators.
*
* @author harald
* @param the enum type
*/
@ValueTranslatorService(modelClass = Enum.class, viewClass = String.class)
public class EnumStringTranslator> extends AbstractValueTranslator {
private final Class clazz; // the enum type
/**
* Creates an enum translator.
*
* @param component the text component
* @param clazz the enum class
*/
public EnumStringTranslator(FxTextComponent component, Class clazz) {
super(component);
this.clazz = clazz;
}
@Override
public Function toViewFunction() {
// toString() and not name() because user's view may be localized
return v -> v == null ? null : v.toString();
}
@Override
public Function toModelFunction() {
return s -> {
if (s != null) {
for (T v: clazz.getEnumConstants()) {
// not Enum.valueOf() because user's view may be localized
if (s.equals(v.toString())) {
return v;
}
}
}
return null;
};
}
}