Learn to Draw Graphics with Swing in Java: A Step-by-Step Guide

In this tutorial, We are going to discuss how to draw graphics using Swing let's get started.





In this tutorial we are going to make a simple application that draws simple graphics like the below:

draw graphics swing using mouse event


Step 1: Create a class named MouseEventEx.java which extends MouseMotionAdapter.

    public class MouseEventEx extends MouseMotionAdapter {


}
Step2: Create an object of JFrame and construct the frame properties


public class MouseEventEx extends MouseMotionAdapter {
JFrame frame = new JFrame();

MouseEventEx(){
frame.setSize(1000,1000);
frame.setVisible(true);
JLabel label = new JLabel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseMotionListener(this);
}


}
Step 3: Create the mouseDragged method which extends from MouseMotionAdapter

public class MouseEventEx extends MouseMotionAdapter {
JFrame frame = new JFrame();

MouseEventEx(){
frame.setSize(1000,1000);
frame.setVisible(true);
JLabel label = new JLabel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me){
Graphics graphics =frame.getGraphics();
graphics.setColor(Color.RED);
graphics.fillOval(me.getX(),me.getY(),30,30);

}

}
Step 4: Create the main  method and create an object of MouseEventEx

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

public class MouseEventEx extends MouseMotionAdapter {
JFrame frame = new JFrame();

MouseEventEx(){
frame.setSize(1000,1000);
frame.setVisible(true);
JLabel label = new JLabel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me){
Graphics graphics =frame.getGraphics();
graphics.setColor(Color.RED);
graphics.fillOval(me.getX(),me.getY(),30,30);

}
public static void main(String[] args) {
new MouseEventEx();
}

}

Reactions

Post a Comment

0 Comments