PROGRAM-10
AIM:- Implement painting using MouseDragged() method of MouseMotionlistener in Applet.
Overview;
Java applets (though deprecated in modern browsers) were used in the past for creating graphical user
interface (GUI) applications embedded in web pages. They were typically used for interactive applications
like games, drawing tools, etc. In this context, we'll focus on creating a simple painting applet that allows
users to draw on the screen using mouse dragging.
In the applet, the mouseDragged() method, part of the MouseMotionListener interface, plays a key
role in capturing mouse drag events. The method is called when the user moves the mouse while holding
down the mouse button, allowing you to capture the dragging motion and update the graphics on the
applet.
Key Concepts in Applet Painting Using mouseDragged():
1. Applet Basics:
o An applet is a special Java program designed to be embedded in a web page and
run inside a browser (though this is now mostly obsolete due to security and
compatibility issues).
o In an applet, you use methods like paint() or update() to perform drawing
tasks.
2. MouseMotionListener:
o The MouseMotionListener interface provides methods to track mouse
movements. The two methods of interest are:
mouseMoved(MouseEvent e): Triggered when the mouse moves but
without being dragged.
mouseDragged(MouseEvent e): Triggered when the mouse moves while
being dragged (with the mouse button held down).
3. mouseDragged() in Action:
o When a user clicks and drags the mouse, the mouseDragged() method is called
continuously, providing the position of the mouse.
o By capturing the current mouse coordinates in this method and updating the
graphics (or storing the mouse positions), you can simulate drawing or painting.
4. Graphics Update:
o Once the mouseDragged() method is invoked, you can use the Graphics object
to draw shapes, lines, or any custom graphics on the applet’s canvas (which is
usually the paint() method).
Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class program_10 extends JFrame {
private final List<Point> points = new ArrayList<>();
public program_10() {
setTitle("Applet Paint App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
DrawingPanel drawingPanel = new DrawingPanel();
add(drawingPanel);
setVisible(true);
}
class DrawingPanel extends JPanel implements MouseMotionListener {
public DrawingPanel() {
addMouseMotionListener(this);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
for (Point p : points) {
g.fillRect(p.x, p.y, 4, 4);
}
}
@Override
public void mouseDragged(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(program_10::new);
}
}
OUTPUT