Elaborate the concept of painting in Java Swing. Illustrate your explanation with a suitable example program

Elaborate the concept of painting in Java Swing. Illustrate your explanation with a suitable example program

Answer:-

Painting in Java Swing

Painting in Java Swing refers to the process of drawing graphics (like shapes, images, or custom UI) on components. This is typically done by overriding the paintComponent() method of a JPanel or other component.


Core Concepts of Painting in Swing

  1. Custom painting is done by overriding paintComponent(Graphics g)
  2. The Graphics object is used to draw shapes, text, images, etc.
  3. Always call super.paintComponent(g) to ensure the component renders correctly before custom drawing.
  4. Repainting is triggered using the repaint() method.

Common Methods of Graphics Class

MethodDescription
drawString(String, x, y)Draws text
drawRect(x, y, width, height)Draws a rectangle
fillRect(x, y, width, height)Fills a rectangle
drawOval(x, y, width, height)Draws an oval
setColor(Color c)Sets the drawing color

Example: Drawing Shapes Using paintComponent()

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

public class PaintingExample extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); // Always call superclass method

        // Set color and draw a rectangle
        g.setColor(Color.BLUE);
        g.fillRect(50, 50, 100, 60);

        // Draw a string
        g.setColor(Color.BLACK);
        g.drawString("Custom Painting", 50, 140);

        // Draw an oval
        g.setColor(Color.RED);
        g.drawOval(200, 50, 100, 60);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Painting in Swing");
        PaintingExample panel = new PaintingExample();

        frame.setSize(400, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setVisible(true);
    }
}

Output Explanation

  • A blue rectangle is filled.
  • A text label is drawn below it.
  • A red oval is drawn to the right.

Summary

  • Painting in Swing is handled using the Graphics object inside paintComponent().
  • Override paintComponent() for custom drawing.
  • repaint() is used to request a redraw.
  • Always use lightweight components like JPanel for custom painting.

Leave a Reply

Your email address will not be published. Required fields are marked *