com.richtodd.android.quiltdesign.block.Swatch.java Source code

Java tutorial

Introduction

Here is the source code for com.richtodd.android.quiltdesign.block.Swatch.java

Source

/* Copyright (c) 2013 Richard G. Todd.
 * Licensed under the terms of the GNU General Public License (GPL) Version 3.0.
 */

package com.richtodd.android.quiltdesign.block;

import java.util.Formatter;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;

public class Swatch implements Comparable<Swatch> {

    //
    // Fields
    //

    private int m_color;

    private String m_sortString = null;
    private float[] m_hsv = new float[3];

    //
    // Constructors
    //

    public Swatch() {
        m_color = 0;
    }

    public Swatch(int color) {
        m_color = color;
    }

    //
    // Public
    //

    public String getDescription() {
        Formatter formatter = new Formatter();
        try {
            formatter.format("#%02x%02x%02x", Color.red(m_color), Color.green(m_color), Color.blue(m_color));
            return formatter.toString();
        } finally {
            formatter.close();
        }
    }

    public int getColor() {
        return m_color;
    }

    public void setColor(int color) {
        m_color = color;
        m_sortString = null;
    }

    public String getSortString() {
        if (m_sortString == null) {
            Color.colorToHSV(m_color, m_hsv);

            Formatter formatter = new Formatter();
            try {
                formatter.format("%03d-%03d-%03d", (int) m_hsv[0], (int) (m_hsv[1] * 100f),
                        (int) (m_hsv[2] * 100f));
                m_sortString = formatter.toString();
            } finally {
                formatter.close();
            }
        }

        return m_sortString;
    }

    //
    // Overrides
    //

    @Override
    public int compareTo(Swatch another) {
        return getSortString().compareTo(another.getSortString());
    }

    //
    // JSON
    //

    JSONObject createJSONObject() throws JSONException {

        JSONObject jsonSwatch = new JSONObject();

        jsonSwatch.put("color", m_color);

        return jsonSwatch;
    }

    static final Swatch createFromJSONObject(JSONObject jsonObject) throws JSONException {

        Swatch swatch = new Swatch();

        swatch.m_color = jsonObject.getInt("color");

        return swatch;
    }
}