import javax.swing.
*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
//This class handles the drawing of the triangle and mouse interactions.
public class TriangleDrawerComponent extends JComponent {
private Point[] points;
private int clickCount;
//Constructor for the points array and sets up the mouse listener
public TriangleDrawerComponent() {
points = new Point[3];
clickCount = 0;
addMouseListener(new MouseAdapter() {
//Handles mouse click events
public void mouseClicked(MouseEvent e) {
if (clickCount < 3) {
points[clickCount] = e.getPoint();
clickCount++;
} else {
// Reset on fourth click
clickCount = 0;
points = new Point[3];
}
repaint(); // Redraw the component
}
});
}
//Paints the component
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Set rendering hints for smoother drawing
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw based on the number of clicks
if (clickCount >= 1) {
// Draw first point
g2d.fill(new Ellipse2D.Double(points[0].x - 2, points[0].y -
2, 4, 4));
}
if (clickCount >= 2) {
// Draw line between first two points
g2d.draw(new Line2D.Double(points[0], points[1]));
}
if (clickCount >= 3) {
// Draw complete triangle
g2d.draw(new Line2D.Double(points[1], points[2]));
g2d.draw(new Line2D.Double(points[2], points[0]));
}
}
}