Sunday, 27 March 2016

Computer Graphics using Java: Java Graphics Programming Lab: Mastering 2D Shapes and Geometric Primitives

Computer Graphics using Java: Java Graphics Programming: Mastering 2D Shapes and Geometric Primitives using JAva 

By: Dr. Zeeshan Bhatti

Basics of Computer Graphics | What is Computer Graphics | Computer Graphics full Course Urdu  🎮02

The Java 2D™ API provides several classes that define common geometric objects such as points, lines, curves, and rectangles. These geometry classes are part of the java.awt.geom package.
The
 PathIterator interface defines methods for retrieving elements from a path.
The
 Shape interface provides a set of methods for describing and inspecting geometric path objects. This interface is implemented by the GeneralPath class and other geometry classes.
All examples represented in this section create geometries by using java.awt.geom and then render them by using the Graphics2D class. To begin you obtain a Graphics2D object, for example by casting theGraphics parameter of the paint() method.
public void paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    ...
}

Lab Objectives

Welcome to Java Graphics Programming! This lab session introduces you to the powerful Java 2D API for creating and manipulating graphical objects. By the end of this lab, you will:

  • Understand the Java 2D rendering model and coordinate system

  • Master the use of geometric primitives from the java.awt.geom package

  • Learn to create points, lines, curves, rectangles, ellipses, and arcs

  • Develop reusable graphics components using object-oriented principles

  • Build complex shapes from basic geometric primitives


Lab Setup and Environment

Required Software:

  • Java Development Kit (JDK) 8 or later

  • Any Java IDE (NetBeans, Eclipse, IntelliJ IDEA) or text editor

  • Basic understanding of Java Swing and AWT

Project Structure:
All graphics operations will be performed within a JFrame's paint() method, using the Graphics2D class for advanced rendering.


Foundation: Understanding the Java 2D API

The Java 2D API provides a comprehensive set of classes for sophisticated graphics programming. Key packages include:

  • java.awt - Basic graphics and GUI components

  • java.awt.geom - Geometric primitives and paths

  • java.awt.image - Image processing classes

Core Concept: All drawing operations are performed through a Graphics2D object, which extends the basic Graphics class with advanced features.


Example 1: Basic Graphics Framework

Description: This example sets up the fundamental structure for all Java 2D graphics programs. It demonstrates how to create a JFrame and override the paint() method for custom drawing.

Java Code:

java
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;

public class BasicGraphicsFrame extends JFrame {
    
    // Constructor to initialize the frame
    public BasicGraphicsFrame() {
        initComponents();
    }
    
    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Java 2D Graphics Lab");
        setSize(600, 500); // Set window size
        setLocationRelativeTo(null); // Center the window
    }
    
    // Override paint method where all drawing occurs
    @Override
    public void paint(Graphics g) {
        super.paint(g); // Call parent paint method for proper rendering
        Graphics2D g2d = (Graphics2D) g; // Cast to Graphics2D for advanced features
        
        // All drawing operations will go here in subsequent examples
        g2d.drawString("Java 2D Graphics - Dr. Zeeshan Bhatti", 50, 50);
    }
    
    public static void main(String[] args) {
        // Create and display the frame
        java.awt.EventQueue.invokeLater(() -> {
            new BasicGraphicsFrame().setVisible(true);
        });
    }
}

Key Points:

  • The paint() method is automatically called when the window needs to be rendered

  • Graphics2D casting enables access to advanced 2D features

  • invokeLater() ensures thread-safe GUI operations


Example 2: Points and Lines

The Point class creates a point representing a location in (x,y) coordinate space. The subclassesPoint2D.Float and Point2D.Double provide correspondingly float and double precision for storing the coordinates of the point.
 
//Create Point2D.Double
Point2D.Double point = new Point2D.Double(x, y);

Line

The Line2D class represents a line segment in (x, y) coordinate space. The Line2D.Float andLine2D.Double subclasses specify lines in float and double precision. For example:
// draw Line2D.Double
g2.draw(new Line2D.Double(x1, y1, x2, y2));


Line

This class includes several setLine() methods to define the endpoints of the line.
Aternatively, the endpoints of the line could be specified by using the constructor for the
 Line2D.Float class as follows:
  • Line2D.Float(float X1, float Y1, float X2, float Y2)
  • Line2D.Float(Point2D p1, Point2D p2)
Use the Stroke object in the Graphics2D class to define the stroke for the line path.

Description: This example demonstrates how to create points and draw lines with different configurations.

Java Code:

java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JFrame;

public class PointsAndLinesExample extends JFrame {
    
    public PointsAndLinesExample() {
        initComponents();
    }
    
    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 500);
        setTitle("Points and Lines Example");
    }
    
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        
        // Enable anti-aliasing for smoother graphics
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                           RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Example 2.1: Creating and drawing points
        Point2D.Double point1 = new Point2D.Double(50, 100);
        Point2D.Double point2 = new Point2D.Double(150, 100);
        
        // Draw points as small circles
        g2d.setColor(Color.RED);
        g2d.fill(new Ellipse2D.Double(point1.getX()-3, point1.getY()-3, 6, 6));
        g2d.fill(new Ellipse2D.Double(point2.getX()-3, point2.getY()-3, 6, 6));
        
        // Example 2.2: Drawing simple lines
        g2d.setColor(Color.BLUE);
        g2d.setStroke(new BasicStroke(2)); // Set line thickness
        
        // Method 1: Using Line2D.Double constructor
        Line2D line1 = new Line2D.Double(50, 120, 200, 120);
        g2d.draw(line1);
        
        // Method 2: Using drawLine method
        g2d.drawLine(50, 140, 200, 140);
        
        // Example 2.3: Multiple lines with different properties
        g2d.setColor(Color.GREEN);
        g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        Line2D thickLine = new Line2D.Double(50, 160, 200, 160);
        g2d.draw(thickLine);
        
        // Example 2.4: Dashed line
        float[] dashPattern = {10, 5, 5, 5}; // Pattern: dash, gap, dash, gap
        g2d.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, 
                                    BasicStroke.JOIN_MITER, 10, dashPattern, 0));
        g2d.setColor(Color.MAGENTA);
        Line2D dashedLine = new Line2D.Double(50, 180, 200, 180);
        g2d.draw(dashedLine);
    }
    
    public static void main(String[] args) {
        new PointsAndLinesExample().setVisible(true);
    }
}

Curves

The java.awt.geom package enables you to create a quadratic or cubic curve segment.
Curve

1.   Quadratic Curve Segment

The QuadCurve2D class implements the Shape interface. This class represents a quadratic parametric curve segment in (x, y) coordinate space. The QuadCurve2D.Float and QuadCurve2D.Double subclasses specify a quadratic curve in float and double precision.
// create new QuadCurve2D.Float
QuadCurve2D q = new QuadCurve2D.Float();
// draw QuadCurve2D.Float with set coordinates
q.setCurve(x1, y1, ctrlx, ctrly, x2, y2);
g2.draw(q);

2.   Cubic Curve Segment

The CubicCurve2D class also implements the Shape interface. This class represents a cubic parametric curve segment in (x, y) coordinate space. CubicCurve2D.Float and CubicCurve2D.Double subclasses specify a cubic curve in float and double precision.
 
// create new CubicCurve2D.Double
CubicCurve2D c = new CubicCurve2D.Double();
// draw CubicCurve2D.Double with set coordinates
c.setCurve(x1, y1, ctrlx1, 
                 ctrly1, ctrlx2, ctrly2, x2, y2);
g2.draw(c);

 Cubic Curve


Rectangle

The Rectangle2D class represents a rectangle defined by a location (x, y) and dimension (w x h). TheRectangle2D.Float and Rectangle2D.Double subclasses specify a rectangle in float and double precision. For example:
// draw Rectangle2D.Double
g2.draw(new Rectangle2D.Double(x, y,
                               rectwidth,
                               rectheight));

The RoundRectangle2D class represents a rectangle with rounded corners defined by a location (x, y), a dimension (w x h), and the width and height of the corner arc. The RoundRectangle2D.Float andRoundRectangle2D.Double subclasses specify a round rectangle in float and double precision.
The rounded rectangle is specified with following parameters:
  • Location
  • Width
  • Height
  • Width of the corner arc
  • Height of the corner acr
To set the location, size, and arcs of a RoundRectangle2D object, use the method setRoundRect(double a, double y, double w, double h, double arcWidth, double arcHeight). For example:
 
// draw RoundRectangle2D.Double
g2.draw(new RoundRectangle2D.Double(x, y,
                                   rectwidth,
                                   rectheight,
                                   10, 10));

 

Example 3: Rectangles and Rounded Rectangles

Description: This example shows how to create various types of rectangles, including rounded rectangles with customizable corner arcs.

Java Code:

java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JFrame;

public class RectanglesExample extends JFrame {
    
    public RectanglesExample() {
        initComponents();
    }
    
    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(700, 600);
        setTitle("Rectangles and Rounded Rectangles");
    }
    
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                           RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Example 3.1: Basic rectangles
        g2d.setColor(Color.BLUE);
        g2d.setStroke(new BasicStroke(2));
        
        // Draw outline rectangle
        Rectangle2D rect1 = new Rectangle2D.Double(50, 80, 120, 80);
        g2d.draw(rect1);
        
        // Draw filled rectangle
        g2d.setColor(new Color(255, 200, 200)); // Light red
        Rectangle2D rect2 = new Rectangle2D.Double(200, 80, 120, 80);
        g2d.fill(rect2);
        
        // Example 3.2: Rounded rectangles
        g2d.setColor(Color.GREEN);
        
        // Rounded rectangle with small corner radius
        RoundRectangle2D roundRect1 = new RoundRectangle2D.Double(50, 200, 120, 80, 20, 20);
        g2d.draw(roundRect1);
        
        // Rounded rectangle with large corner radius (almost circular)
        g2d.setColor(new Color(100, 100, 255));
        RoundRectangle2D roundRect2 = new RoundRectangle2D.Double(200, 200, 120, 80, 60, 60);
        g2d.fill(roundRect2);
        
        // Example 3.3: Different stroke for rectangles
        g2d.setColor(Color.ORANGE);
        g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER));
        Rectangle2D thickRect = new Rectangle2D.Double(350, 80, 120, 80);
        g2d.draw(thickRect);
        
        // Example 3.4: Gradient filled rectangle
        GradientPaint gradient = new GradientPaint(350, 200, Color.RED, 
                                                 450, 280, Color.YELLOW);
        g2d.setPaint(gradient);
        Rectangle2D gradientRect = new Rectangle2D.Double(350, 200, 100, 80);
        g2d.fill(gradientRect);
    }
    
    public static void main(String[] args) {
        new RectanglesExample().setVisible(true);
    }
}

Ellipse

The Ellipse2D class represents an ellipse defined by a bounding rectangle. The Ellipse2D.Float andEllipse2D.Double subclasses specify an ellipse in float and double precision.
Ellipse is fully defined by a location, a width and a height. For example:
// draw Ellipse2D.Double
g2.draw(new Ellipse2D.Double(x, y,
                             rectwidth,
                             rectheight));

Arc

To draw a piece of an ellipse, you use the Arc2D class. This class represents an arc defined by a bounding rectangle, a start angle, an angular extent, and a closure type. The Arc2D.Float and Arc2D.Doublesubclasses specify an ellipse in float and double precision.
The Arc2D class defines the following three types of arcs, represented by corresponding constants in this class: OPEN, PIE and CHORD.
Several methods set the size and parameters of the arc:
  • Directly, by coordinates
  • By supplied Point2D and Dimension2D
  • By copying an existing Arc2D
Also, you can use the setArcByCenter method to specify an arc from a center point, given by its coordinates and a radius.
// draw Arc2D.Double
g2.draw(new Arc2D.Double(x, y,
                         rectwidth,
                         rectheight,
                         90, 135,
                         Arc2D.OPEN));



Example 4: Ellipses, Arcs, and Curves

Description: This comprehensive example demonstrates circles, ellipses, arcs, and both quadratic and cubic Bézier curves.

Java Code:

java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JFrame;

public class CurvesAndEllipsesExample extends JFrame {
    
    public CurvesAndEllipsesExample() {
        initComponents();
    }
    
    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 700);
        setTitle("Ellipses, Arcs and Curves");
    }
    
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                           RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Example 4.1: Ellipses and Circles
        g2d.setColor(Color.BLUE);
        g2d.setStroke(new BasicStroke(2));
        
        // Draw ellipse
        Ellipse2D ellipse = new Ellipse2D.Double(50, 80, 150, 100);
        g2d.draw(ellipse);
        
        // Draw circle (ellipse with equal width and height)
        g2d.setColor(Color.RED);
        Ellipse2D circle = new Ellipse2D.Double(250, 80, 100, 100);
        g2d.draw(circle);
        
        // Example 4.2: Arcs with different types
        g2d.setColor(Color.GREEN);
        
        // OPEN arc (default)
        Arc2D openArc = new Arc2D.Double(50, 220, 100, 100, 45, 90, Arc2D.OPEN);
        g2d.draw(openArc);
        
        // CHORD arc (connected with straight line)
        g2d.setColor(Color.MAGENTA);
        Arc2D chordArc = new Arc2D.Double(180, 220, 100, 100, 45, 90, Arc2D.CHORD);
        g2d.draw(chordArc);
        
        // PIE arc (connected to center)
        g2d.setColor(Color.ORANGE);
        Arc2D pieArc = new Arc2D.Double(310, 220, 100, 100, 45, 90, Arc2D.PIE);
        g2d.fill(pieArc); // Using fill for better visualization
        
        // Example 4.3: Quadratic Bézier Curve
        g2d.setColor(Color.BLUE);
        QuadCurve2D quadCurve = new QuadCurve2D.Double();
        quadCurve.setCurve(50, 350, 150, 300, 250, 350); // (startX, startY, controlX, controlY, endX, endY)
        g2d.draw(quadCurve);
        
        // Draw control points for visualization
        g2d.setColor(Color.RED);
        g2d.fillOval(145, 295, 10, 10); // Control point
        
        // Example 4.4: Cubic Bézier Curve
        g2d.setColor(new Color(0, 150, 0)); // Dark green
        CubicCurve2D cubicCurve = new CubicCurve2D.Double();
        cubicCurve.setCurve(300, 350, 350, 300, 450, 400, 500, 350);
        g2d.draw(cubicCurve);
        
        // Draw control points
        g2d.setColor(Color.RED);
        g2d.fillOval(345, 295, 10, 10); // First control point
        g2d.fillOval(445, 395, 10, 10); // Second control point
        
        // Example 4.5: Complex shape using GeneralPath
        g2d.setColor(new Color(128, 0, 128)); // Purple
        GeneralPath complexShape = new GeneralPath();
        complexShape.moveTo(500, 100); // Starting point
        complexShape.lineTo(550, 150);
        complexShape.curveTo(570, 130, 580, 110, 560, 90); // Cubic curve
        complexShape.quadTo(540, 70, 500, 100); // Quadratic curve back to start
        complexShape.closePath(); // Close the shape
        g2d.draw(complexShape);
    }
    
    public static void main(String[] args) {
        new CurvesAndEllipsesExample().setVisible(true);
    }
}

Example 5: Advanced Graphics - Colors, Gradients, and Transformations

Description: This example demonstrates advanced Java 2D features including color blending, gradient fills, and geometric transformations.

Java Code:

java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.JFrame;

public class AdvancedGraphicsExample extends JFrame {
    
    public AdvancedGraphicsExample() {
        initComponents();
    }
    
    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setTitle("Advanced Java 2D Graphics");
    }
    
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                           RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Example 5.1: Gradient Fills
        // Linear gradient
        GradientPaint linearGradient = new GradientPaint(50, 50, Color.RED, 
                                                       200, 50, Color.BLUE);
        g2d.setPaint(linearGradient);
        g2d.fill(new Rectangle2D.Double(50, 50, 150, 100));
        
        // Radial gradient
        RadialGradientPaint radialGradient = new RadialGradientPaint(
            300, 100, 50, new float[]{0.0f, 1.0f}, 
            new Color[]{Color.YELLOW, Color.RED});
        g2d.setPaint(radialGradient);
        g2d.fill(new Ellipse2D.Double(250, 50, 100, 100));
        
        // Example 5.2: Transparency (Alpha compositing)
        g2d.setColor(new Color(0, 255, 0, 128)); // Green with 50% transparency
        g2d.fill(new Rectangle2D.Double(400, 50, 100, 100));
        
        g2d.setColor(new Color(255, 0, 0, 128)); // Red with 50% transparency
        g2d.fill(new Rectangle2D.Double(450, 80, 100, 100));
        
        // Example 5.3: Geometric Transformations
        // Save original transformation
        AffineTransform originalTransform = g2d.getTransform();
        
        // Translation
        g2d.setColor(Color.BLUE);
        g2d.translate(100, 250);
        g2d.draw(new Rectangle2D.Double(0, 0, 80, 60));
        
        // Rotation
        g2d.setColor(Color.RED);
        g2d.rotate(Math.toRadians(45)); // Rotate 45 degrees
        g2d.draw(new Rectangle2D.Double(0, 0, 80, 60));
        
        // Restore original transformation
        g2d.setTransform(originalTransform);
        
        // Scaling
        g2d.setColor(Color.GREEN);
        g2d.translate(300, 250);
        g2d.scale(1.5, 0.8); // Scale X by 1.5, Y by 0.8
        g2d.draw(new Rectangle2D.Double(0, 0, 80, 60));
        
        // Restore for next operations
        g2d.setTransform(originalTransform);
        
        // Example 5.4: Shearing transformation
        g2d.setColor(Color.MAGENTA);
        g2d.translate(500, 250);
        g2d.shear(0.3, 0.1); // Shear in X and Y directions
        g2d.draw(new Rectangle2D.Double(0, 0, 80, 60));
    }
    
    public static void main(String[] args) {
        new AdvancedGraphicsExample().setVisible(true);
    }
}

Lab Exercises and Tasks

Task 1: Create a program that draws a national flag using rectangles and appropriate colors.

Task 2: Implement a simple bar chart showing student marks using rectangles of different heights.

Task 3: Create an animated sunrise scene using arcs (sun) and lines (sun rays).

Task 4: Draw a simple house with windows, door, and roof using combinations of rectangles, lines, and polygons.

Task 5: Create a program that draws your university logo using basic geometric shapes.


Lab Submission Requirements

  1. Source Code: Submit all .java files for each example and task

  2. Output Screenshots: Capture and submit screenshots of each program's output

  3. Documentation: Include comments explaining your code logic

  4. Lab Report: Write a brief report discussing what you learned and challenges faced

Remember: Understanding these Java 2D fundamentals is crucial for advanced graphics programming and game development!

Instructor: Prof. Dr. Zeeshan Bhatti
YouTube Channel: Zeeshan Academy



Sample Program

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.*;

public class Java2DFrame extends javax.swing.JFrame {
   
    public Java2DFrame() {
        initComponents();
    }
   
    /**
     * This is the method where the graphic objects are drawn.
     *
     */
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Line2D lin = new Line2D.Float(100, 100, 250, 260);
        g2.draw(lin);
       
        g2.draw(new Rectangle2D.Double(10, 50, 100, 100));
                              
         g2.draw(new RoundRectangle2D.Double(200, 200, 100, 100,  50, 50));                     
    }
   
     private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        this.setBounds(0,0,400,400);
        this.setLayout(null);
        pack();
    }
   
    /**
     * Starts the program
     *
     */
    public static void main(String args[]) {
                new Java2DFrame().setVisible(true);
    }
}



5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Some working frameworks naturally conceal record exentions and I prescribe fixing that if you're planing on working in the realm of outline and programing as its basic for you to dependably realize what document sorts are before you. Java

    ReplyDelete
  3. These handsouts by Sir Zeeshan Bhatti are very important in order to learn the basic of java programming. Please upload its pdf file so that students could download it later.

    ReplyDelete
  4. Web surfers are jagged on information overload. If they don't see what they would like to see on your property page or a landing page, they bounce. small business web design melbourne

    ReplyDelete

Featured post

The 10-Minute App Lie? We Challenge Vibe Coding to Create a Working Mobile App!

Vibe Coding The 10-Minute App Lie? We Challenge Vibe Coding to Create a Working Mobile App! Meta Description: Can you really build a functio...