Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright 2008-2011 the original author or authors.
 *
 * 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.
 */

import java.awt.*;
import java.awt.image.BufferedImage;

public class Main {
    /**
     * Takes a snapshot of the target component.
     *
     * @param component the component to draw
     * @return a Graphics compatible image of the component
     */
    public static Image takeSnapshot(Component component) {
        return takeSnapshot(component, false);
    }

    /**
     * Takes a snapshot of the target component.
     *
     * @param component the component to draw
     * @param usePrint  whether <tt>print()</tt> or <tt>paint()</tt> is used to grab the snapshot
     * @return a Graphics compatible image of the component
     */
    public static Image takeSnapshot(Component component, boolean usePrint) {
        BufferedImage image = null;
        GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = genv.getDefaultScreenDevice();
        GraphicsConfiguration gc = gd.getDefaultConfiguration();

        if (gc.getColorModel().hasAlpha()) {
            image = gc.createCompatibleImage((int) component.getSize().getWidth(),
                    (int) component.getSize().getHeight());
        } else {
            image = new BufferedImage((int) component.getSize().getWidth(), (int) component.getSize().getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
        }

        Graphics g = image.getGraphics();
        if (usePrint) {
            component.print(g);
        } else {
            component.paint(g);
        }
        g.dispose();

        return image;
    }
}