Skip to content
Unit 4 Syllabus Note· GUI Programming

GUI Programming

Comprehensive exam revision notes for BCA-432E Unit 4 (ADO.NET Architecture & Database Connectivity). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

GUI Programming

ADO.NET Architecture & Database Connectivity

Core Definitions & Key Concepts

What is the Graphics Context in Java (java.awt.Graphics)

The Graphics context is an abstract drawing surface representing the device screen or offscreen image, encapsulating state such as current color, font, clipping rectangle, and primitive drawing methods (drawLine, drawRect, drawString).

What is the difference between Graphics and Graphics2D

Graphics2D extends Graphics (Java 2D API) to provide advanced rendering features: floating-point coordinates, stroke thickness/dashing, gradient/texture paints, affine coordinate transformations, and antialiased rendering hints.

Why should you override paintComponent(Graphics g) instead of paint(Graphics g) in Swing

Because paint() manages three sub-methods: paintComponent() (background and component body), paintBorder() (borders), and paintChildren() (child widgets). Overriding paint() directly breaks Swing double-buffering and child component clipping.

What is the purpose of super.paintComponent(g)

It clears the background and handles proper UI delegate rendering. Omitting super.paintComponent(g) causes visual artifact ghosting when dragging windows or components.

What is Double Buffering in GUI graphics

A rendering technique where drawing operations are executed offscreen in a secondary memory buffer (back buffer) and copied to the visible screen buffer in a single blit operation, eliminating visible screen flicker during complex animations.

What is an AffineTransform in Java 2D

A 2D coordinate transformation that preserves collinearity (points on a line remain on a line) and ratios of distances, supporting translation, rotation, scaling, and shearing via a 3 × 3 matrix.

Rendering Hints (RenderingHints) in Java 2D

Key-value settings passed to Graphics2D.setRenderingHint() that control the trade-off between rendering speed and visual quality (e.g., antialiasing for text and curves).

How do you specify custom colors and font styles in Java AWT

  • Color: new Color(int r, int g, int b, int alpha) (RGB 0–255, alpha transparency).
  • Font: new Font(String name, int style, int size) (styles: Font.PLAIN, Font.BOLD, Font.ITALIC).

What is FontMetrics in Java

A class (java.awt.FontMetrics) that provides physical typographical dimensions for a specific font on a graphics device: ascent (height above baseline), descent (depth below baseline), leading (line spacing), and stringWidth (pixel length).

What is the repaint() method

An asynchronous request to the Event Dispatch Thread to re-render the component. It marks the component as damaged and schedules a call to paintComponent() without blocking the calling thread.

Conceptual & Architectural Analysis

The Java 2D Rendering Pipeline with an ASCII Architecture Diagram

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ Primitive Shape / Text / Image ]
               |
               v
  [ Coordinate Transformation (AffineTransform) ]
               |
               v
  [ Stroke & Outline Generation (BasicStroke) ]
               |
               v
  [ Clipping (Clip Shape Intersection) ]
               |
               v
  [ Paint Shading (Color / GradientPaint / TexturePaint) ]
               |
               v
  [ Composite / Alpha Blending (AlphaComposite) ]
               |
               v
  [ Rasterizer & RenderingHints (Antialiasing) ]
               |
               v
        [ Frame Buffer / Display ]

Compare paint(), paintComponent(), and repaint()

MethodResponsibilityInvoked ByOverridden by Developer?
`paint(g)`High-level orchestrator for component, borders, and childrenAWT subsystemRarely in Swing
`paintComponent(g)`Custom graphics rendering of the component bodypaint(g)Yes (Primary extension point)
`repaint()`Requests asynchronous redraw; batches damaged areasUser code / Event handlersNever (Call only)

Double Buffering Mechanics and How Swing Implements It Natively

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ WITHOUT DOUBLE BUFFERING ]
Screen Buffer: Clear -> Draw Line -> Draw Box -> Draw Text (Eye sees flashes -> FLICKER!)

[ WITH DOUBLE BUFFERING ]
Back Buffer (Offscreen RAM): Clear -> Draw Line -> Draw Box -> Draw Text (Hidden)
          |
          +---> Instant Memory Blit (Single Frame Step) ---> [ Front Buffer (Display) ] (NO FLICKER!)
  • In Swing, double buffering is enabled by default for all JComponent instances (setDoubleBuffered(true)).

FontMetrics Typographical Geometry

System Architecture / Concept DiagramHorizontal Scroll Enabled
       Top line ------------------------------------------------+
                 Ascent                                         |
       Baseline  -------------------- "BCA Student" ------------+ Height
                 Descent                                        |
       Bottom    ------------------------------------------------+
                 Leading (Line spacing to next line)
  • Center text horizontally: int x = (panelWidth - metrics.stringWidth(text)) / 2;

Java 2D Gradient Paint and Texture Paint

  • `GradientPaint`: Smoothly blends colors between two specified coordinates (linear interpolation).
  • `TexturePaint`: Repeats a tiled BufferedImage across a geometric shape.

In-Depth Analysis & Implementation

Develop a Custom Circular Progress Gauge Component with Antialiasing, Gradient Shading, and Dynamic Value Animation

System Architecture / Concept DiagramHorizontal Scroll Enabled
package com.mjpru.bca.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;

public class CircularProgressGauge extends JComponent {
    private int progress = 0; // 0 to 100

    public CircularProgressGauge() {
        setPreferredSize(new Dimension(160, 160));
    }

    public void setProgress(int value) {
        this.progress = Math.max(0, Math.min(100, value));
        repaint(); // Trigger repaint on EDT
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();

        // Enable high-quality antialiasing
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        int size = Math.min(getWidth(), getHeight()) - 20;
        int x = (getWidth() - size) / 2;
        int y = (getHeight() - size) / 2;
        int strokeWidth = 14;

        // 1. Draw Background Track Ring
        g2.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g2.setColor(new Color(226, 232, 240));
        g2.draw(new Ellipse2D.Float(x, y, size, size));

        // 2. Draw Active Progress Arc with Gradient
        GradientPaint gradient = new GradientPaint(
            x, y, new Color(59, 130, 246),
            x + size, y + size, new Color(16, 185, 129)
        );
        g2.setPaint(gradient);
        float extent = -(progress / 100.0f) * 360.0f;
        g2.draw(new Arc2D.Float(x, y, size, size, 90, extent, Arc2D.OPEN));

        // 3. Render Center Typography
        g2.setColor(new Color(15, 23, 42));
        g2.setFont(new Font("Segoe UI", Font.BOLD, 24));
        String text = progress + "%";
        FontMetrics fm = g2.getFontMetrics();
        int textX = (getWidth() - fm.stringWidth(text)) / 2;
        int textY = (getHeight() + fm.getAscent() - fm.getDescent()) / 2;
        g2.drawString(text, textX, textY);

        g2.dispose(); // Release graphics resources
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom Gauge Component");
            frame.setSize(300, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setLayout(new BorderLayout());

            CircularProgressGauge gauge = new CircularProgressGauge();
            frame.add(gauge, BorderLayout.CENTER);
            frame.setVisible(true);

            // Animate progress 0 to 100 with Timer
            Timer timer = new Timer(30, null);
            timer.addActionListener(e -> {
                int next = (gauge.progress + 1) % 101;
                gauge.setProgress(next);
            });
            timer.start();
        });
    }
}

Java 2D Coordinate Transformations: Translation, Rotation, and Scaling via AffineTransform

Java
1@Override
2protected void paintComponent(Graphics g) {
3 super.paintComponent(g);
4 Graphics2D g2d = (Graphics2D) g.create();
5
6 // Translate origin to center of panel
7 g2d.translate(getWidth() / 2, getHeight() / 2);
8
9 // Rotate coordinate system by 45 degrees
10 g2d.rotate(Math.toRadians(45));
11
12 // Scale axes
13 g2d.scale(1.5, 1.5);
14
15 // Draw square at new local origin
16 g2d.setColor(Color.RED);
17 g2d.fillRect(-25, -25, 50, 50);
18
19 g2d.dispose();
20}

Double Buffering Implementation from Scratch using Offscreen BufferedImage

Manual Offscreen Double Buffering Implementation

System Architecture / Concept DiagramHorizontal Scroll Enabled
public class OffscreenDoubleBufferCanvas extends JPanel {
    private BufferedImage offscreenBuffer;

    @Override
    protected void paintComponent(Graphics g) {
        // 1. Create or resize offscreen image
        if (offscreenBuffer == null || 
            offscreenBuffer.getWidth() != getWidth() || 
            offscreenBuffer.getHeight() != getHeight()) {
            offscreenBuffer = (BufferedImage) createImage(getWidth(), getHeight());
        }

        // 2. Draw all complex primitives to the offscreen buffer
        Graphics2D offG = offscreenBuffer.createGraphics();
        offG.setColor(Color.WHITE);
        offG.fillRect(0, 0, getWidth(), getHeight());
        
        // Render complex scene
        offG.setColor(Color.BLUE);
        offG.fillOval(50, 50, 100, 100);
        offG.dispose();

        // 3. Single-blit offscreen image to visible screen
        g.drawImage(offscreenBuffer, 0, 0, this);
    }
}

Important Exam Points & Quick Revision

Examiners frequently ask: paintComponent vs paint and role of super.paintComponent (10 marks), Double Buffering mechanics, and Graphics2D vs Graphics differences.

Your reading progress
0%

100% left on this page — finishing it closes the gap for ADO.NET Architecture & Database Connectivity.

Weak topic hint

ADO.NET Architecture & Database Connectivity still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.