Utils.java Source code

Java tutorial

Introduction

Here is the source code for Utils.java

Source

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.com (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;
    }
}