parse Colour - Java 2D Graphics

Java examples for 2D Graphics:Graphics

Description

parse Colour

Demo Code

/*/*from   w w  w.  ja  v a  2s  . com*/
This file is part of leafdigital util.

util is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

util 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with util.  If not, see <http://www.gnu.org/licenses/>.

Copyright 2011 Samuel Marshall.
 */
//package com.java2s;
import java.awt.*;

public class Main {
    /**
     * @param s Colour string #rrggbb or #rgb
     * @return Colour object
     * @throws NumberFormatException If the format doesn't match
     */
    public static Color parseColour(String s) {
        if (s.matches("#[0-9a-fA-F]{6}")) {
            try {
                return new Color(Integer.parseInt(s.substring(1, 3), 16),
                        Integer.parseInt(s.substring(3, 5), 16),
                        Integer.parseInt(s.substring(5, 7), 16));
            } catch (NumberFormatException nfe) {
                throw new NumberFormatException("Invalid colour syntax '"
                        + s + "' expecting #rrggbb");
            }
        } else if (s.matches("#[0-9a-fA-F]{3}")) {
            try {
                int r = Integer.parseInt(s.substring(1, 2), 16), g = Integer
                        .parseInt(s.substring(2, 3), 16), b = Integer
                        .parseInt(s.substring(3, 4), 16);
                r = r + (16 * r);
                g = g + (16 * g);
                b = b + (16 * b);
                return new Color(r, g, b);
            } catch (NumberFormatException nfe) {
                throw new NumberFormatException("Invalid colour syntax '"
                        + s + "' expecting #rgb");
            }
        } else {
            throw new NumberFormatException("Invalid colour syntax '" + s
                    + "' expecting #rgb or #rrggbb");
        }
    }
}

Related Tutorials