The following code demonstrates How to Use Graphics in AWT.

Problem Statement

Develop a Java application that shows working with Graphics, colors, and fonts in AWT.


Creating a Java application that demonstrates working with Graphics, colors, and fonts in AWT involves using the Graphics class to draw shapes, apply colors, and set fonts. The following code shows an example of a Java application that showcases these concepts.

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

public class GraphicsDemo extends JFrame {
    public GraphicsDemo() {
        setTitle("Graphics, Colors, and Fonts Demo");
        setSize(400, 300);
        add(new DrawingPanel());

    class DrawingPanel extends JPanel {
        protected void paintComponent(Graphics g) {

            // Set background color

            // Set font and draw text
            Font font = new Font("Arial", Font.BOLD, 20);
            g.drawString("Graphics Demo", 100, 30);

            // Draw shapes
            g.drawRect(50, 50, 100, 50); // Rectangle
            g.fillOval(200, 50, 80, 80); // Filled oval
            g.drawLine(50, 200, 250, 200); // Line

            // Draw a custom shape
            int[] xPoints = {150, 200, 100};
            int[] yPoints = {250, 300, 300};
            int numPoints = 3;
            g.fillPolygon(xPoints, yPoints, numPoints);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new GraphicsDemo();

In this program:

  1. We create a GraphicsDemo class that extends JFrame to create the main window.
  2. Inside the constructor:
    • We set the title, size, close operation, and add a custom DrawingPanel to the frame.
  3. The DrawingPanel class is an inner class that extends JPanel and overrides its paintComponent method. Inside this method, we:
    • Set the background color of the panel to light gray.
    • Also, set the font and draw text using drawString.
    • Draw various shapes such as rectangles, ovals, lines, and a custom polygon using different colors.
  4. Then, we set the main background color of the panel to light gray using setBackground.
  5. In the main method, we use SwingUtilities.invokeLater to create an instance of the GraphicsDemo on the Swing Event Dispatch Thread.

When you run this program, you’ll see a GUI window displaying text and various shapes, demonstrating the use of graphics, colors, and fonts in AWT.

Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise