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.

PDF Creation / Manipulation in JAVA

Writing to PDF is very easy with Lowagie’s iText package.

Program below demonstrates how easily one can create, update and manipulate pdf files (including pdf merging) in Java.

package com.kushal.util;

import java.io.FileOutputStream;
import java.util.HashMap;

import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class PDFManipulation {

public static void main(String[] args) {
try {
	// we create a reader for a certain document
	PdfReader reader = new PdfReader(
		"D:/GeneralWs/utilities/com/kushal/util/FormToFill.pdf");
	int n = reader.getNumberOfPages();
	// we create a stamper that will copy the document to a new file
	PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(
			"myOutPutFile.pdf"));
	// adding some metadata
	HashMap moreInfo = new HashMap();
	moreInfo.put("Author", "Kushal Paudyal");
	stamp.setMoreInfo(moreInfo);
	// adding content to each page
	int i = 0;
	PdfContentByte under;
	PdfContentByte over;

	Image img = Image
	.getInstance("D:/GeneralWs/utilities/com/kushal/util/Flood.jpg");

	BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN,
			BaseFont.WINANSI, BaseFont.EMBEDDED);
	img.setAbsolutePosition(400, 400);
	while (i < n) {
		i++;
		// watermark under the existing page
		under = stamp.getUnderContent(i);
		under.addImage(img);
		// text over the existing page
		over = stamp.getOverContent(i);
		over.beginText();
		over.setFontAndSize(bf, 18);
		over.setTextMatrix(30, 30);
		over.showText("page " + i);
		over.setFontAndSize(bf, 26);

		over.showTextAligned(Element.ALIGN_LEFT, 
		   "12N00607", 400, 730,0);
		over.endText();

	}
	// adding an extra page
	stamp.insertPage(1, PageSize.A4);
	over = stamp.getOverContent(1);
	over.beginText();
	over.setFontAndSize(bf, 18);
	over.showTextAligned(Element.ALIGN_LEFT,
		"DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
	over.endText();
	// adding a page from another document
	PdfReader rdr = new PdfReader("C:/secondFile.pdf");
	under = stamp.getUnderContent(1);
	under.addTemplate(stamp.getImportedPage(rdr, 3), 1, 0, 0, 1, 0,
			0);
	// closing PdfStamper will generate the new PDF file
	stamp.close();
} catch (Exception de) {
	de.printStackTrace();
}
}
}

Lifecycle of a Java Servlet – three basic phases of initialize, service and destroy

The total life cycle of a java Servlet lies between the beginning of the servlet loading into the application server memory and ending of the servlet by termination/reload.

Basically there are three phases in the life-cycle of a java servlet.

  • Instantiation and Initialization Phase (using init() method)
  1. Creates the instance of the servlet
  2. If successfully instantiated, the servlet is available for providing service
  3. If failed to instantiate, it will unload the servlet
  • Servicing Phase (using service() method)
  1. Gets information about the request from the request object
  2. Processes the request
  3. Uses methods of the response object to create the client response.
  4. Can invoke other methods to process the request, such as doGet(), doPost(), or other custom methods.
  • Termination Phase (using destroy() methods)
  • Stops a servlet by invoking the servlet’s destroy() method.
  • The destroy() method runs only one time during the lifetime of the servlet and signals the end of the servlet.
  • After calling destroy() method, the servlet engine unloads the servlet
  • Unloaded servlets are collected by JVM Garbage Collection