Java examples for 2D Graphics:Color String
Parses a color instance from the given hex string.
/**//from w w w .j a v a 2 s .co m * This class offers a few utility methods useful when handling Colors. * <p/> * <hr/> Copyright 2006-2012 Torsten Heup * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ //package com.java2s; import java.awt.*; public class Main { public static void main(String[] argv) throws Exception { String string = "java2s.com"; System.out.println(fromHexString(string)); } /** * Parses a color instance from the given hex string. * * @param string string to parse color value from. * @return a color instance parsed from the given hex string. */ public static Color fromHexString(final String string) { if (string == null) throw new IllegalArgumentException( "Parameter 'string' must not be null!"); final int color = Integer.parseInt(string, 16); return new Color(color, color > 0xFFFFFF); } /** * Parses a color instance from the given hex string and replaces its alpha value with the given parameter. * * @param string string to parse color value from. * @param alpha the alpha value to apply to the color. * @return a color instance parsed from the given hex string. */ public static Color fromHexString(final String string, final int alpha) { if (string == null) throw new IllegalArgumentException( "Parameter 'string' must not be null!"); if (alpha < 0 || alpha > 255) throw new IllegalArgumentException("Illegal alpha value: " + alpha + ", expected a value between 0 and 255"); final int color = (Integer.parseInt(string, 16) & 0xFFFFFF) | (alpha << 24); return new Color(color, true); } }