Obtain a java.awt.Paint instance which draws a checker background of black and white. - Java 2D Graphics

Java examples for 2D Graphics:Paint

Description

Obtain a java.awt.Paint instance which draws a checker background of black and white.

Demo Code

/*/*from  w  w  w .j a v a  2s. c o  m*/
 * $Id: ColorUtil.java,v 1.12 2009/05/25 01:52:13 kschaefe Exp $
 *
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * 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
 */
//package com.java2s;
import java.awt.Color;
import java.awt.Graphics;

import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getCheckerPaint());
    }

    /**
     * Obtain a <code>java.awt.Paint</code> instance which draws a checker
     * background of black and white. 
     * Note: The returned instance may be shared.
     * Note: This method should be reimplemented to not use a png resource.
     *
     * @return a Paint implementation
     */
    public static Paint getCheckerPaint() {
        return getCheckerPaint(Color.white, Color.gray, 20);
    }

    public static Paint getCheckerPaint(Color c1, Color c2, int size) {
        BufferedImage img = new BufferedImage(size, size,
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = img.getGraphics();

        try {
            g.setColor(c1);
            g.fillRect(0, 0, size, size);
            g.setColor(c2);
            g.fillRect(0, 0, size / 2, size / 2);
            g.fillRect(size / 2, size / 2, size / 2, size / 2);
        } finally {
            g.dispose();
        }

        return new TexturePaint(img, new Rectangle(0, 0, size, size));
    }
}

Related Tutorials