Java 2D Graphics Example Tutorial On Paint, Gradient and Stroke

Java 2D is an API for drawing two-dimensional graphics using the Java programming language. Every Java 2D drawing operation can ultimately be treated as filling a shape using a paint and compositing the result onto the screen. The following example will demonstrate:

  • – How to define JAVA 2D Shape
  • – How to define Gradient Paint
  • – How to set Graphics paint
  • – How to relocate the java 2D frame for redrawing
  • – How to set the strokes in the Graphics
  • – How to fill shapes with color or gradient

You will also be learning

  • – How to center your GUI on the screen automatically.
package com.kushal.graphics;
/**
 * Java 2D Graphics Example Tutorial On Paint, Gradient and Stroke
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 10th August 2009
 */

import java.awt.*;
import java.awt.geom.*;

import javax.swing.JFrame;

public class JavaPaintAndStroke extends JFrame {

	private static final long serialVersionUID = 7944800805864455013L;

	public static void main(String[] args) {
		JavaPaintAndStroke paintFrame = new JavaPaintAndStroke();
		paintFrame.setTitle("Sanjaal.com/java - GUI Tutorial");
		paintFrame.setSize(350, 200);
		paintFrame.setVisible(true);
		paintFrame.centerTheGUIFrame(paintFrame);

	}

	public void paint(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		double x = 20, y = 60, w = 80, h = 80;
		/** Defining a rectangle and a gradient **/
		Rectangle2D r = new Rectangle2D.Double(x, y, w, h);
		GradientPaint gp = new GradientPaint(75, 75, Color.red, 95, 95,
				Color.green, true);

		/**
		 * Filling the rectangle with a gradient paint
		 */
		g2.setPaint(gp);
		g2.fill(r);

		/**
		 * Shifting the frame to the right by 100
		 * Then using Stroke With a Solid Color
		 *
		 * setFrame method below sets the location and size of
		 * the outer bounds of this Rectangle2D to the
		 * specified rectangular values.
		 *
		 * x, y locations
		 * w, h width and height of new Rectangle frame
		 */
		r.setFrame(x + 100, y, w, h);
		g2.setPaint(Color.red);
		g2.setStroke(new BasicStroke(8));
		g2.draw(r);

		/**
		 * Shifting the original rectangle frame to the right by 200
		 * Then using a Stroke With a Gradient Color
		 */
		r.setFrame(x + 200, y, w, h);
		g2.setPaint(gp);
		g2.draw(r);
	}

	/**
	 * This method is used to center the GUI
	 * @param frame - Frame that needs to be centered.
	 */
	public void centerTheGUIFrame(JFrame frame) {
		int widthWindow = frame.getWidth();
		int heightWindow = frame.getHeight();

		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		int X = (screen.width / 2) - (widthWindow / 2); // Center horizontally.
		int Y = (screen.height / 2) - (heightWindow / 2); // Center vertically.

		frame.setBounds(X, Y, widthWindow, heightWindow);

	}
}

==========================
The following is the output of this program.

Originally posted 2009-08-10 14:38:17.

Share

How to capture a screenshot using Java and save it to a file?

A screenshot, screen capture, or screen dump is an image taken by the computer to record the visible items displayed on the monitor or another visual output device. Usually this is a digital image taken by the host operating system or software running on the computer device, but it can also be a capture made by a camera or a device intercepting the video output of the computer.

Screenshots, screen dumps, or screen captures can be used to demonstrate a program, a particular problem a user might be having or generally when computer output needs to be shown to others or archived, or to simply show off what you do on your computer to others. [Wikipedia]

The following java program demonstrates how to use Robot class from java.awt package to capture screenshots and save the image thus captured to disk.

package com.kushal.utils;

/**
 * @author Kushal Paudyal
 * JavaScreenCaptureUtil.java
 * 
 * This utility captures the screenshot and saves
 * the captured image to disk.
 */
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.imageio.ImageIO;

public class JavaScreenCaptureUtil {

	public static void main(String args[]) throws Exception {

		/**
		 * This class (Robot.java) is used to generate native system input events for the 
		 * purposes of test automation, self-running demos, and other 
		 * applications where control of the mouse and keyboard is needed. 
		 * The primary purpose of Robot is to facilitate automated testing 
		 * of Java platform implementations. 
		 */
		Robot robot = new Robot();
		
		/**
		 * Get the current screen dimensions.
		 */
		Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
		int width = (int) d.getWidth();
		int height = (int) d.getHeight();
		
		
		/**
		 * Delay the robot for 5 seconds (5000 ms) allowing you to switch to proper
		 * screen/window whose screenshot is to be taken.
		 * 
		 * You can change the delay time as required.
		 */
		robot.delay(5000);
		
		/**
		 * Create a screen capture of the active window and then create a buffered image
		 * to be saved to disk.
		 */
		Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
				height));

		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);

		/**
		 * Filename where to save the file to.
		 * I am appending formatted timestamp to the filename.
		 */
		String fileNameToSaveTo = "C:/temp/screenCapture_"
				+ createTimeStampStr() + ".PNG";
		
		/**
		 * Write the captured image to a file.
		 * I am using PNG format. You can choose PNG, JPG, GIF.
		 */
		writeImage(bi, fileNameToSaveTo, "PNG");

		System.out.println("Screen Captured Successfully and Saved to:\n"+fileNameToSaveTo);

	}

	/**
	 * This method writes a buffered image to a file
	 * 
	 * @param img -- > BufferedImage
	 * @param fileLocation --> e.g. "C:/testImage.jpg"
	 * @param extension --> e.g. "jpg","gif","png"
	 */
	public static void writeImage(BufferedImage img, String fileLocation,
			String extension) {
		try {
			BufferedImage bi = img;
			File outputfile = new File(fileLocation);
			ImageIO.write(bi, extension, outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @return String representation of timestamp 
	 * in the format of yyyyMMdd_hhmmss (e.g. 20100426_111612)
	 * @throws Exception
	 */
	public static String createTimeStampStr() throws Exception {
		Calendar mycalendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
		String timeStamp = formatter.format(mycalendar.getTime());

		return timeStamp;

	}

       /*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
	 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
	 * LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
	 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
	 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 * 
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */

}

Blog Widget by LinkWithin

Originally posted 2010-04-26 12:12:19.

Share