001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.preferences; 003 004import java.awt.Color; 005import java.util.Locale; 006 007import org.openstreetmap.josm.tools.ColorHelper; 008 009/** 010 * A property containing a {@link Color} value. 011 * @since 5464 012 */ 013public class ColorProperty extends AbstractToStringProperty<Color> { 014 015 private final String name; 016 017 /** 018 * Constructs a new {@code ColorProperty}. 019 * @param colName The color name 020 * @param defaultValue The default value as HTML string 021 */ 022 public ColorProperty(String colName, String defaultValue) { 023 this(colName, defaultValue == null ? null : ColorHelper.html2color(defaultValue)); 024 } 025 026 /** 027 * Constructs a new {@code ColorProperty}. 028 * @param colName The color name 029 * @param defaultValue The default value 030 */ 031 public ColorProperty(String colName, Color defaultValue) { 032 super(getColorKey(colName), defaultValue); 033 this.name = colName; 034 getPreferences().registerColor(getColorKey(colName), colName); 035 } 036 037 @Override 038 public Color get() { 039 // Removing this implementation breaks binary compatibility due to the way generics work 040 return super.get(); 041 } 042 043 @Override 044 public boolean put(Color value) { 045 // Removing this implementation breaks binary compatibility due to the way generics work 046 return super.put(value); 047 } 048 049 @Override 050 protected Color fromString(String string) { 051 return ColorHelper.html2color(string); 052 } 053 054 @Override 055 protected String toString(Color t) { 056 return ColorHelper.color2html(t, true); 057 } 058 059 /** 060 * Gets a color of which the value can be set. 061 * @param colorName the name of the color. 062 * @return The child property that inherits this value if it is not set. 063 */ 064 public AbstractToStringProperty<Color> getChildColor(String colorName) { 065 return getChildProperty(getColorKey(colorName)); 066 } 067 068 /** 069 * Gets the name this color was registered with. 070 * @return The name. 071 */ 072 public String getName() { 073 return name; 074 } 075 076 /** 077 * Replies the color key used in JOSM preferences for this property. 078 * @param colName The color name 079 * @return The color key for this property 080 */ 081 public static String getColorKey(String colName) { 082 return colName == null ? null : "color." + colName.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z0-9]+", "."); 083 } 084 085 @Override 086 public String toString() { 087 return "ColorProperty [name=" + name + ", defaultValue=" + getDefaultValue() + "]"; 088 } 089}