001 /*
002 * Databinder: a simple bridge from Wicket to Hibernate
003 * Copyright (C) 2006 Nathan Hamblen nathan@technically.us
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either
008 * version 2.1 of the License, or (at your option) any later version.
009 *
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
013 * Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public
016 * License along with this library; if not, write to the Free Software
017 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
018 */
019
020 package net.databinder.converters;
021
022 import java.awt.Color;
023 import java.util.Locale;
024
025 import org.apache.wicket.util.convert.ConversionException;
026 import org.apache.wicket.util.convert.converters.AbstractConverter;
027 import org.apache.wicket.util.string.Strings;
028
029 /**
030 * Convert between a HTML hex color string and java.awt.Color.
031 * @author Nathan Hamblen
032 * @see Color
033 */
034 public class ColorConverter extends AbstractConverter {
035
036 @Override
037 protected Class getTargetType() {
038 return Color.class;
039 }
040
041 public Object convertToObject(String str, Locale loc) {
042 try {
043 if (Strings.isEmpty(str)) return null;
044 return Color.decode(str.toString());
045 } catch (NumberFormatException e) {
046 throw new ConversionException(e);
047 }
048 }
049 @Override
050 public String convertToString(Object value, Locale locale) {
051 if (value == null) return null;
052 Color c = (Color) value;
053 return "#" + Integer.toHexString(c.getRGB()).substring(2);
054 }
055 }