Java Tutorial/2D Graphics/Color

Материал из Java эксперт
Версия от 15:25, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Color class is used to work with colors in Java 2D

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Colors extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(new Color(12, 16, 116));
    g2d.fillRect(10, 15, 90, 60);
    g2d.setColor(new Color(42, 19, 31));
    g2d.fillRect(130, 15, 90, 60);
    g2d.setColor(new Color(70, 7, 23));
    g2d.fillRect(250, 15, 90, 60);
    g2d.setColor(new Color(10, 10, 84));
    g2d.fillRect(10, 105, 90, 60);
    g2d.setColor(new Color(22, 21, 61));
    g2d.fillRect(130, 105, 90, 60);
    g2d.setColor(new Color(21, 98, 69));
    g2d.fillRect(250, 105, 90, 60);
    g2d.setColor(new Color(217, 146, 54));
    g2d.fillRect(10, 195, 90, 60);
    g2d.setColor(new Color(63, 121, 186));
    g2d.fillRect(130, 195, 90, 60);
    g2d.setColor(new Color(131, 121, 11));
    g2d.fillRect(250, 195, 90, 60);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Colors");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Colors());
    frame.setSize(360, 300);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Color Factory

/*
    GNU LESSER GENERAL PUBLIC LICENSE
    Copyright (C) 2006 The Lobo Project
    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    Contact info: lobochief@users.sourceforge.net
*/
/*
 * Created on Apr 17, 2005
 */
import java.util.*;
import java.util.logging.*;
import java.awt.*;
/**
 * @author J. H. S.
 */
public class ColorFactory {
  private static final Logger logger = Logger.getLogger(ColorFactory.class.getName());
  public static final Color TRANSPARENT = new Color(0, 0, 0, 0);
  private static ColorFactory instance;
  private final Map colorMap = new HashMap(256);
  
  private ColorFactory() {
    Map colorMap = this.colorMap;
    synchronized(this) {      
      colorMap.put("transparent", TRANSPARENT);
      //http://www.w3schools.ru/css/css_colornames.asp
      colorMap.put("aliceblue", new Color(0xf0f8ff));
      colorMap.put("antiquewhite", new Color(0xfaebd7));
      colorMap.put("aqua", new Color(0x00ffff));
      colorMap.put("aquamarine", new Color(0x7fffd4));
      colorMap.put("azure", new Color(0xf0ffff));
      colorMap.put("beige", new Color(0xf5f5dc));
      colorMap.put("bisque", new Color(0xffe4c4));
      colorMap.put("black", new Color(0x000000));
      colorMap.put("blanchedalmond", new Color(0xffebcd));
      colorMap.put("blue", new Color(0x0000ff));
      colorMap.put("blueviolet", new Color(0x8a2be2));
      colorMap.put("brown", new Color(0xa52a2a));
      colorMap.put("burlywood", new Color(0xdeb887));
      colorMap.put("cadetblue", new Color(0x5f9ea0));
      colorMap.put("chartreuse", new Color(0x7fff00));
      colorMap.put("chocolate", new Color(0xd2691e));
      colorMap.put("coral", new Color(0xff7f50));
      colorMap.put("cornflowerblue", new Color(0x6495ed));
      colorMap.put("cornsilk", new Color(0xfff8dc));
      colorMap.put("crimson", new Color(0xdc143c));
      colorMap.put("cyan", new Color(0x00ffff));
      colorMap.put("darkblue", new Color(0x00008b));
      colorMap.put("darkcyan", new Color(0x008b8b));
      colorMap.put("darkgoldenrod", new Color(0xb8860b));
      colorMap.put("darkgray", new Color(0xa9a9a9));
      colorMap.put("darkgrey", new Color(0xa9a9a9));
      colorMap.put("darkgreen", new Color(0x006400));
      colorMap.put("darkkhaki", new Color(0xbdb76b));
      colorMap.put("darkmagenta", new Color(0x8b008b));
      colorMap.put("darkolivegreen", new Color(0x556b2f));
      colorMap.put("darkorange", new Color(0xff8c00));
      colorMap.put("darkorchid", new Color(0x9932cc));
      colorMap.put("darkred", new Color(0x8b0000));
      colorMap.put("darksalmon", new Color(0xe9967a));
      colorMap.put("darkseagreen", new Color(0x8fbc8f));
      colorMap.put("darkslateblue", new Color(0x483d8b));
      colorMap.put("darkslategray", new Color(0x2f4f4f));
      colorMap.put("darkslategrey", new Color(0x2f4f4f));
      colorMap.put("darkturquoise", new Color(0x00ced1));
      colorMap.put("darkviolet", new Color(0x9400d3));
      colorMap.put("deeppink", new Color(0xff1493));
      colorMap.put("deepskyblue", new Color(0x00bfff));
      colorMap.put("dimgray", new Color(0x696969));
      colorMap.put("dimgrey", new Color(0x696969));
      colorMap.put("dodgerblue", new Color(0x1e90ff));
      colorMap.put("firebrick", new Color(0xb22222));
      colorMap.put("floralwhite", new Color(0xfffaf0));
      colorMap.put("forestgreen", new Color(0x228b22));
      colorMap.put("fuchsia", new Color(0xff00ff));
      colorMap.put("gainsboro", new Color(0xdcdcdc));
      colorMap.put("ghostwhite", new Color(0xf8f8ff));
      colorMap.put("gold", new Color(0xffd700));
      colorMap.put("goldenrod", new Color(0xdaa520));
      colorMap.put("gray", new Color(0x808080));
      colorMap.put("grey", new Color(0x808080));
      colorMap.put("green", new Color(0x008000));
      colorMap.put("greenyellow", new Color(0xadff2f));
      colorMap.put("honeydew", new Color(0xf0fff0));
      colorMap.put("hotpink", new Color(0xff69b4));
      colorMap.put("indianred", new Color(0xcd5c5c));
      colorMap.put("indigo", new Color(0x4b0082));
      colorMap.put("ivory", new Color(0xfffff0));
      colorMap.put("khaki", new Color(0xf0e68c));
      colorMap.put("lavender", new Color(0xe6e6fa));
      colorMap.put("lavenderblush", new Color(0xfff0f5));
      colorMap.put("lawngreen", new Color(0x7cfc00));
      colorMap.put("lemonchiffon", new Color(0xfffacd));
      colorMap.put("lightblue", new Color(0xadd8e6));
      colorMap.put("lightcoral", new Color(0xf08080));
      colorMap.put("lightcyan", new Color(0xe0ffff));
      colorMap.put("lightgoldenrodyellow", new Color(0xfafad2));
      colorMap.put("lightgray", new Color(0xd3d3d3));
      colorMap.put("lightgrey", new Color(0xd3d3d3));
      colorMap.put("lightgreen", new Color(0x90ee90));
      colorMap.put("lightpink", new Color(0xffb6c1));
      colorMap.put("lightsalmon", new Color(0xffa07a));
      colorMap.put("lightseagreen", new Color(0x20b2aa));
      colorMap.put("lightskyblue", new Color(0x87cefa));
      colorMap.put("lightslategray", new Color(0x778899));
      colorMap.put("lightslategrey", new Color(0x778899));
      colorMap.put("lightsteelblue", new Color(0xb0c4de));
      colorMap.put("lightyellow", new Color(0xffffe0));
      colorMap.put("lime", new Color(0x00ff00));
      colorMap.put("limegreen", new Color(0x32cd32));
      colorMap.put("linen", new Color(0xfaf0e6));
      colorMap.put("magenta", new Color(0xff00ff));
      colorMap.put("maroon", new Color(0x800000));
      colorMap.put("mediumaquamarine", new Color(0x66cdaa));
      colorMap.put("mediumblue", new Color(0x0000cd));
      colorMap.put("mediumorchid", new Color(0xba55d3));
      colorMap.put("mediumpurple", new Color(0x9370d8));
      colorMap.put("mediumseagreen", new Color(0x3cb371));
      colorMap.put("mediumslateblue", new Color(0x7b68ee));
      colorMap.put("mediumspringgreen", new Color(0x00fa9a));
      colorMap.put("mediumturquoise", new Color(0x48d1cc));
      colorMap.put("mediumvioletred", new Color(0xc71585));
      colorMap.put("midnightblue", new Color(0x191970));
      colorMap.put("mintcream", new Color(0xf5fffa));
      colorMap.put("mistyrose", new Color(0xffe4e1));
      colorMap.put("moccasin", new Color(0xffe4b5));
      colorMap.put("navajowhite", new Color(0xffdead));
      colorMap.put("navy", new Color(0x000080));
      colorMap.put("oldlace", new Color(0xfdf5e6));
      colorMap.put("olive", new Color(0x808000));
      colorMap.put("olivedrab", new Color(0x6b8e23));
      colorMap.put("orange", new Color(0xffa500));
      colorMap.put("orangered", new Color(0xff4500));
      colorMap.put("orchid", new Color(0xda70d6));
      colorMap.put("palegoldenrod", new Color(0xeee8aa));
      colorMap.put("palegreen", new Color(0x98fb98));
      colorMap.put("paleturquoise", new Color(0xafeeee));
      colorMap.put("palevioletred", new Color(0xd87093));
      colorMap.put("papayawhip", new Color(0xffefd5));
      colorMap.put("peachpuff", new Color(0xffdab9));
      colorMap.put("peru", new Color(0xcd853f));
      colorMap.put("pink", new Color(0xffc0cb));
      colorMap.put("plum", new Color(0xdda0dd));
      colorMap.put("powderblue", new Color(0xb0e0e6));
      colorMap.put("purple", new Color(0x800080));
      colorMap.put("red", new Color(0xff0000));
      colorMap.put("rosybrown", new Color(0xbc8f8f));
      colorMap.put("royalblue", new Color(0x4169e1));
      colorMap.put("saddlebrown", new Color(0x8b4513));
      colorMap.put("salmon", new Color(0xfa8072));
      colorMap.put("sandybrown", new Color(0xf4a460));
      colorMap.put("seagreen", new Color(0x2e8b57));
      colorMap.put("seashell", new Color(0xfff5ee));
      colorMap.put("sienna", new Color(0xa0522d));
      colorMap.put("silver", new Color(0xc0c0c0));
      colorMap.put("skyblue", new Color(0x87ceeb));
      colorMap.put("slateblue", new Color(0x6a5acd));
      colorMap.put("slategray", new Color(0x708090));
      colorMap.put("slategrey", new Color(0x708090));
      colorMap.put("snow", new Color(0xfffafa));
      colorMap.put("springgreen", new Color(0x00ff7f));
      colorMap.put("steelblue", new Color(0x4682b4));
      colorMap.put("tan", new Color(0xd2b48c));
      colorMap.put("teal", new Color(0x008080));
      colorMap.put("thistle", new Color(0xd8bfd8));
      colorMap.put("tomato", new Color(0xff6347));
      colorMap.put("turquoise", new Color(0x40e0d0));
      colorMap.put("violet", new Color(0xee82ee));
      colorMap.put("wheat", new Color(0xf5deb3));
      colorMap.put("white", new Color(0xffffff));
      colorMap.put("whitesmoke", new Color(0xf5f5f5));
      colorMap.put("yellow", new Color(0xffff00));
      colorMap.put("yellowgreen", new Color(0x9acd32));
    }
  } 
  public static final ColorFactory getInstance() {
    if(instance == null) {
      synchronized(ColorFactory.class) {
        if(instance == null) {
          instance = new ColorFactory();
        }
      }
    }
    return instance;
  }
  
  private static final String RGB_START = "rgb(";
  
  public boolean isColor(String colorSpec) {
    if(colorSpec.startsWith("#")) {
      return true;
    }
    String normalSpec = colorSpec.toLowerCase();
    if(normalSpec.startsWith(RGB_START)) {
      return true;
    }
    synchronized(this) {
      return colorMap.containsKey(normalSpec);
    }
  }
  
  public Color getColor(String colorSpec) {
    String normalSpec = colorSpec.toLowerCase();
    synchronized(this) {
      Color color = (Color) colorMap.get(normalSpec);
      if(color == null) {
        if(normalSpec.startsWith(RGB_START)) {
          // CssParser produces this format.          
          int endIdx = normalSpec.lastIndexOf(")");
          String commaValues = endIdx == -1 ? normalSpec.substring(RGB_START.length()) : normalSpec.substring(RGB_START.length(), endIdx);
          StringTokenizer tok = new StringTokenizer(commaValues, ",");
          int r = 0, g = 0, b = 0;
          if(tok.hasMoreTokens()) {
            String rstr = tok.nextToken().trim();
            try {
              r = Integer.parseInt(rstr);
            } catch(NumberFormatException nfe) {
              // ignore
            }
            if(tok.hasMoreTokens()) {
              String gstr = tok.nextToken().trim();
              try {
                g = Integer.parseInt(gstr);
              } catch(NumberFormatException nfe) {
                // ignore
              }
              if(tok.hasMoreTokens()) {
                String bstr = tok.nextToken().trim();
                try {
                  b = Integer.parseInt(bstr);
                } catch(NumberFormatException nfe) {
                  // ignore
                }
              }
            }
          }
          color = new Color(r, g, b);
        }
        else if(normalSpec.startsWith("#")) {
          //TODO: OPTIMIZE: It would be more efficient to
          //create new Color(hex), but CssParser doesn"t
          //give us values formatted with "#" either way.
          int len = normalSpec.length();
          int[] rgba = new int[4];
          rgba[3] = 255;
          for(int i = 0; i < rgba.length; i++) 
          {
            int idx = 2 * i + 1;
            if(idx < len) 
            {
              String hexText = normalSpec.substring(idx, idx + Math.min(2, len - idx));
              try {
                rgba[i] = Integer.parseInt(hexText, 16);
              } catch(NumberFormatException nfe) {
                // Ignore
              }
            }
          }       
          color = new Color(rgba[0], rgba[1], rgba[2], rgba[3]);
        }
        else {
          if(logger.isLoggable(Level.INFO)) {
            logger.warning("getColor(): Color spec [" + normalSpec + "] unknown.");
          }
          return Color.RED;
        }
        colorMap.put(normalSpec, color);
      }
      return color;
    }
  }
  
  
}





Construct Color object

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ColorSample {
  public static void main(String args[]) {
    JFrame f = new JFrame("JColorChooser Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JButton button = new JButton("Pick to Change Background");
    Color myBlack = new Color(0,0,0);           // Color black
//    Color myWhite = new Color(255,255,255);     // Color white
  //  Color myGreen = new Color(0,200,0);         // A shade of green
    
    button.setBackground(myBlack);
    f.add(button, BorderLayout.CENTER);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





Constructs several colors and draws various objects using these colors:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ColorVariousObjects extends JFrame {
  public static void main(String[] a){
    ColorVariousObjects f = new ColorVariousObjects();
    f.setSize(300,300);
    f.setVisible(true);
  }
  
  
  public void paint(Graphics g) {
    Color c1 = new Color(255, 100, 100);
    Color c2 = new Color(100, 255, 100);
    Color c3 = new Color(100, 100, 255);
    g.setColor(c1);
    g.drawLine(0, 0, 100, 100);
    g.drawLine(0, 100, 100, 0);
    g.setColor(c2);
    g.drawLine(40, 25, 250, 180);
    g.drawLine(75, 90, 400, 400);
    g.setColor(c3);
    g.drawLine(20, 150, 400, 40);
    g.drawLine(5, 290, 80, 19);
    g.setColor(Color.red);
    g.drawOval(10, 10, 50, 50);
    g.fillOval(70, 90, 140, 100);
    g.setColor(Color.blue);
    g.drawOval(190, 10, 90, 30);
    g.drawRect(10, 10, 60, 50);
    g.setColor(Color.cyan);
    g.fillRect(100, 10, 60, 50);
    g.drawRoundRect(190, 10, 60, 50, 15, 15);
  }
}





Convert an integer to an HTML RGB value

/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/
/**
 * Collection of string utilities.
 * 
 */
public class StringUtil
{
  /**
   * Convert an integer to an HTML RGB value. The result is of the form
   * #hhhhhh. The input rgb integer value will be clipped into the range 0 ~
   * 0xFFFFFF
   * 
   * @param rgb
   *            the integer RGB value
   * @return the value as an HTML RGB string
   */
  public static String toRgbText( int rgb )
  {
    // clip input value.
    if ( rgb > 0xFFFFFF )
      rgb = 0xFFFFFF;
    if ( rgb < 0 )
      rgb = 0;
    String str = "000000" + Integer.toHexString( rgb ); //$NON-NLS-1$ 
    return "#" + str.substring( str.length( ) - 6 ); //$NON-NLS-1$ 
  }
}





Convert HSB to RGB value

import java.awt.Color;
public class Main {
  public static void main() {
    float hue = 12; 
    float saturation = 13;
    float brightness = 14;
    
    int rgb = Color.HSBtoRGB(hue, saturation, brightness);
    int red = (rgb >> 16) & 0xFF;
    int green = (rgb >> 8) & 0xFF;
    int blue = rgb & 0xFF;
  }
}





Convert RGB to HSB

import java.awt.Color;
public class Main {
  public static void main() {
    int red = 23;
    int green = 66;
    int blue = 99;
    float[] hsb = Color.RGBtoHSB(red, green, blue, null);
    float hue = hsb[0]; 
    float saturation = hsb[1];
    float brightness = hsb[2];
  }
}





Converts a given string into a color.

import java.awt.Color;
import java.lang.reflect.Field;
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 * 
 * -------------------
 * PaintUtilities.java
 * -------------------
 * (C) Copyright 2003-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: PaintUtilities.java,v 1.10 2007/11/02 17:50:37 taqua Exp $
 *
 * Changes
 * -------
 * 13-Nov-2003 : Version 1 (DG);
 * 04-Oct-2004 : Renamed PaintUtils --> PaintUtilities (DG);
 * 23-Feb-2005 : Rewrote equal() method with less indenting required (DG);
 *
 */
public class Main {
  /**
   * Converts a given string into a color.
   * 
   * @param value
   *          the string, either a name or a hex-string.
   * @return the color.
   */
  public static Color stringToColor(final String value) {
    if (value == null) {
      return Color.black;
    }
    try {
      // get color by hex or octal value
      return Color.decode(value);
    } catch (NumberFormatException nfe) {
      // if we can"t decode lets try to get it by name
      try {
        // try to get a color by name using reflection
        final Field f = Color.class.getField(value);
        return (Color) f.get(null);
      } catch (Exception ce) {
        // if we can"t get any color return black
        return Color.black;
      }
    }
  }
}





Converts the String representation of a color to an actual Color object.

import java.awt.Color;
/*
 * Copyright 2007 Google Inc.
 *
 * 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
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */
/**
 * Some string utilities for joining list of strings.
 *
 * @author ycoppel@google.ru (Yohann Coppel)
 *
 */
public class Utils {
  
  /**
   * Converts the <code>String</code> representation of a color to an actual
   * <code>Color</code> object.
   *
   * @param value String representation of the color in "r,g,b" format (e.g.
   * "100,255,0")
   * @return <code>Color</code> object that matches the red-green-blue values
   * provided by the parameter. Returns <code>null</code> for empty string.
   */
  public static Color stringToColor(String value) {
    try {
      if (!value.equals("")) {
        String[] s = value.split(",");
        if (s.length == 3) {
          int red = Integer.parseInt(s[0]);
          int green = Integer.parseInt(s[1]);
          int blue = Integer.parseInt(s[2]);
          return new Color(red, green, blue);
        }
      }
    } catch (NumberFormatException ex) {
      // ignore it, don"t change anything.
      return null;
    } catch (IllegalArgumentException ex) {
      // if a user entered 548 as the red value....
      // ignore it, don"t change anything.
      return null;
    }
    return null;
  }
}





Derives a color by adding the specified offsets to the base color"s hue, saturation, and brightness values

/*
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.awt.Color;
/**
*
* @author aim
*/
public class Utils {
  /**
   * Derives a color by adding the specified offsets to the base color"s 
   * hue, saturation, and brightness values.   The resulting hue, saturation,
   * and brightness values will be contrained to be between 0 and 1.
   * @param base the color to which the HSV offsets will be added
   * @param dH the offset for hue
   * @param dS the offset for saturation
   * @param dB the offset for brightness
   * @return Color with modified HSV values
   */
  public static Color deriveColorHSB(Color base, float dH, float dS, float dB) {
      float hsb[] = Color.RGBtoHSB(
              base.getRed(), base.getGreen(), base.getBlue(), null);
      hsb[0] += dH;
      hsb[1] += dS;
      hsb[2] += dB;
      return Color.getHSBColor(
              hsb[0] < 0? 0 : (hsb[0] > 1? 1 : hsb[0]),
              hsb[1] < 0? 0 : (hsb[1] > 1? 1 : hsb[1]),
              hsb[2] < 0? 0 : (hsb[2] > 1? 1 : hsb[2]));
                                             
  }
}





Drawing with Color

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.red);
    g2d.fill(new Rectangle(20,20,200,200));
    int red = 230;
    int green = 45;
    int blue = 67;
    g2d.setColor(new Color(red, green, blue));
    g2d.fill(new Rectangle(40,40,200,200));
  }
}





Get HTML Color String from Java Color object

import java.awt.Color;
public class Utils {
  public static String getHTMLColorString(Color color) {
    String red = Integer.toHexString(color.getRed());
    String green = Integer.toHexString(color.getGreen());
    String blue = Integer.toHexString(color.getBlue());
    return "#" + 
            (red.length() == 1? "0" + red : red) +
            (green.length() == 1? "0" + green : green) +
            (blue.length() == 1? "0" + blue : blue);        
}
}





HTML color and Java Color

/**
 * Licensed under the Common Development and Distribution License,
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.sun.ru/cddl/
 *   
 * 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.
 */
//Revised from ajax4jsf
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shura (latest modification by $Author: slava_kabanovich $)
 * @version $Revision: 1.2 $ $Date: 2006/07/12 14:59:33 $
 *
 */
public class HtmlColor {
  private static Map colorNames;
  
  static {
    // color names.
    colorNames = new HashMap();
      colorNames.put("black", new Color(0x000000));
    colorNames.put("green", new Color(0x008000));
    colorNames.put("silver", new Color(0xC0C0C0));
    colorNames.put("lime", new Color(0x00FF00));
    colorNames.put("gray", new Color(0x808080));
    colorNames.put("olive", new Color(0x808000));
    colorNames.put("white", new Color(0xFFFFFF));
    colorNames.put("yellow", new Color(0xFFFF00));
    colorNames.put("maroon", new Color(0x800000));
    colorNames.put("navy", new Color(0x000080));
    colorNames.put("red", new Color(0xFF0000));
    colorNames.put("blue", new Color(0x0000FF));
    colorNames.put("purple", new Color(0x800080));
    colorNames.put("teal", new Color(0x008080));
    colorNames.put("fuchsia", new Color(0xFF00FF));
    colorNames.put("aqua", new Color(0x00FFFF));
  }
  /**
   * Decode HTML-attribute style of color to {@link Color}
   * @param color - color name or #RRGGBB string
   * @return - color for this value.
   */
  public static Color decode(String color){
    if(null == color) {
      throw new IllegalArgumentException("NULL_COLOR_PARAMETER_ERROR");
    }
    Color c = (Color) colorNames.get(color.trim().toLowerCase());
    if (null == c) {
      try {
        c = Color.decode(color.trim());
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException("DECODE_COLOR_PARAMETER_ERROR");
      }
    }
    return c;
  }
  
  public static Integer integerValue(String color){
    return new Integer(decode(color).getRGB());
  }
  
  public static String encodeRGB(Color color){
    if(null == color) {
      throw new IllegalArgumentException("NULL_COLOR_PARAMETER_ERROR_2");
    }
    return "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase();
  }
  
}





java.awt.Color

A Color object represents a color. Color class provides static fields that return a specific Color object: BLACK, BLUE, GREEN, RED, CYAN, ORANGE, YELLOW.

For example, to obtain a Color object that represents green, use this code:



Color color = Color.GREEN;





Java Predefined Colors

Predefined ColorRGB Valuesblack(0,0,0)blue(0,0,255)cyan(0,255,255)darkGray(64,64,64)gray(128,128,128)green(0,255,0)lightGray(192,192,192)magenta(255,0,255)orange(255,200,0)pink(255,175,175)red(255,0,0)white(255,255,255)yellow(255,255,0)


Map colors into names and vice versa.

/**
 * 
 * LibSparkline : a free Java sparkline chart library
 * 
 *
 * Project Info:  http://reporting.pentaho.org/libsparkline/
 *
 * (C) Copyright 2008, by Larry Ogrodnek, Pentaho Corporation and Contributors.
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the Apache License 2.0.
 *
 * 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.
 *
 * You should have received a copy of the Apache License 2.0 along with this library;
 * if not, a online version is available at http://www.apache.org/licenses/
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ------------
 * ColorUtilitiy.java
 * ------------
 */
import java.awt.Color;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
/**
 * A helper class to map colors into names and vice versa.
 * 
 * @author Thomas Morgner
 */
public final class ColorUtilitiy {
  private static final HashMap knownColorNamesByColor;
  private static final HashMap knownColorsByName;
  static {
    knownColorNamesByColor = new HashMap();
    knownColorsByName = new HashMap();
    try {
      final Field[] fields = Color.class.getFields();
      for (int i = 0; i < fields.length; i++) {
        final Field f = fields[i];
        if (Modifier.isPublic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())
            && Modifier.isStatic(f.getModifiers())) {
          final String name = f.getName();
          final Object oColor = f.get(null);
          if (oColor instanceof Color) {
            knownColorNamesByColor.put(oColor, name.toLowerCase());
            knownColorsByName.put(name.toLowerCase(), oColor);
          }
        }
      }
    } catch (Exception e) {
      // ignore ..
    }
  }
  /**
   * Utility class constructor prevents object creation.
   */
  private ColorUtilitiy() {
  }
  /**
   * Parse a String into a Color. <p/> This method will accept either a color
   * name (a field name from {@link Color}, case insensitive e.g. "red"), or a
   * HTML hex color string (e.g. "#ff0000" for Color.RED).
   * 
   * @param value
   *          String to parse for color name or color number.
   * @return Color for s.
   */
  private static Color parseColor(final String value) {
    if (value == null) {
      return null;
    }
    final Object o = knownColorsByName.get(value.toLowerCase());
    if (o != null) {
      return (Color) o;
    }
    try {
      // get color by hex or octal value
      return Color.decode(value.trim());
    } catch (NumberFormatException nfe) {
      return null;
    }
  }
  /**
   * Parse a String into a Color, and returns the given default value if the
   * color is not parsable. <p/> This method will accept either a color name (a
   * field name from {@link Color}, case insensitive e.g. "red"), or a HTML hex
   * color string (e.g. "#ff0000" for Color.RED).
   * 
   * @param colorText
   *          String to parse for color name or color number.
   * @param defValue
   *          the default value that should be returned if the string is not
   *          parseable or null.
   * @return Color for the text.
   */
  public static Color convertColor(final String colorText, final Color defValue) {
    if (colorText == null || colorText.isEmpty()) {
      return defValue;
    }
    final Color retval = parseColor(colorText);
    if (retval == null) {
      return defValue;
    }
    return retval;
  }
}





Set XOR mode to color blue

// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski.  Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class xorTest extends JPanel{
    public void init () {
        setBackground (Color.red);
    }
    public void paint (Graphics g) {
        g.setColor (Color.green);
        g.setXORMode (Color.blue);
        g.fillRect (10, 10, 100, 100);
        g.fillRect (10, 60, 100, 100);
    }
    public static void main(String[] a){
      JFrame f = new JFrame();
      f.add(new xorTest());
      f.setSize(300,300);
      f.setVisible(true);
    }
}





To compare two Color objects you can use the equals() method

import java.awt.Color;
public class MainClass {
  public static void main(String[] a) {
    Color myBlack = new Color(0, 0, 0); // Color black
    Color myWhite = new Color(255, 255, 255); // Color white
    System.out.println(myBlack.equals(myWhite));
  }
}



false


Using color with and Bit and

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  Color[] colors = new Color[24];
  public MyCanvas() {
    int  rgb = 0xff;
    for (int i = 0; i < 24; i++) {
      colors[i] = new Color(rgb);
      rgb <<= 1;
      if ((rgb & 0x1000000) != 0) {
        rgb |= 1;
        rgb &= 0xffffff;
      }
    }
  }
  public void paint(Graphics g) {
    int i = 10;
    for (Color c : colors) {
      g.setColor(c);
      i += 10;
      g.drawLine(i, 10, 200, 200);
    }
  }
}
public class DrawLine {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Using the getRGB() method for comparing colors

import java.awt.Color;
public class MainClass {
  public static void main(String[] a) {
    Color myBlack = new Color(0, 0, 0); // Color black
    Color myWhite = new Color(255, 255, 255); // Color white
    System.out.println(myBlack.getRGB() == myWhite.getRGB());
    System.out.println(myBlack.getRGB());
    System.out.println(myWhite.getRGB());
  }
}



false
-16777216
-1