Java
Java

 

Introduction

Drawing apps are widely used in various creative fields, from sketching to graphic design. The goal of this program is to create a basic drawing application that allows users to draw freehand on a canvas using a mouse. This will introduce you to the concepts of graphical user interfaces (GUIs) and event handling in Java.

In this application, users can click and drag the mouse to draw on a canvas. This program will demonstrate how to work with Java’s javax.swing package, which provides classes for building GUI applications, and how to handle mouse events to capture user input.

Objective

The objectives of this program are:

  • Allow the user to draw freehand on a canvas by clicking and dragging the mouse.
  • Provide a simple GUI with a basic drawing area where the user can create sketches.
  • Utilize Java’s Swing and AWT libraries to handle GUI components and mouse events.

Code

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

public class DrawingApp extends JFrame {

    private int x1, y1, x2, y2;

    public DrawingApp() {
        setTitle("Basic Drawing App");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // Panel where the drawing will take place
        DrawingPanel panel = new DrawingPanel();
        add(panel);

        // Make the window visible
        setVisible(true);
    }

    // Inner class for the drawing panel
    class DrawingPanel extends JPanel {
        
        public DrawingPanel() {
            // MouseListener to handle mouse events
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    // Set initial point when mouse is pressed
                    x1 = e.getX();
                    y1 = e.getY();
                }
            });

            // MouseMotionListener to handle mouse drag events
            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    // Get current point while dragging
                    x2 = e.getX();
                    y2 = e.getY();

                    // Draw a line from the previous point to the current point
                    Graphics g = getGraphics();
                    g.drawLine(x1, y1, x2, y2);

                    // Update the previous point to the current point for the next drag
                    x1 = x2;
                    y1 = y2;
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Set up the drawing settings (color, stroke, etc.)
            g.setColor(Color.BLACK);
        }
    }

    public static void main(String[] args) {
        // Run the drawing app
        SwingUtilities.invokeLater(() -> new DrawingApp());
    }
}

Program Explanation

The program is designed to let users draw freehand on a canvas using a mouse. Let’s break down its key components:

  • DrawingApp Class: This is the main class that sets up the window, also known as a JFrame. It includes basic configurations such as the title, size, and default close operation. The drawing area is provided by a DrawingPanel class that is added to the frame.
  • DrawingPanel Class: This class extends JPanel and overrides the paintComponent method, which is responsible for rendering the graphics on the screen. The paintComponent method is called whenever the panel needs to be redrawn. Here, it’s used to set up the drawing color (black in this case).
  • Mouse Handling: The program uses two mouse event listeners:
    • MouseListener: It listens for when the mouse is pressed, capturing the initial coordinates (x1, y1) where the drawing starts.
    • MouseMotionListener: It listens for when the mouse is dragged, capturing the current coordinates (x2, y2). A line is drawn between the previous and current points using the drawLine method.
  • Graphics Object: The Graphics object is used to perform the actual drawing on the screen. Each time the user drags the mouse, a line is drawn between the previous and current mouse coordinates.

How to Run the Program

Follow these steps to run the program:

  1. Save the code in a file named DrawingApp.java.
  2. Open a terminal or command prompt and navigate to the directory where the file is saved.
  3. Compile the program with the Java compiler:
    javac DrawingApp.java
  4. Run the program:
    java DrawingApp
  5. A window will open where you can click and drag the mouse to draw freehand on the canvas.
© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)