hi
I need to make a simple program to draw fillRect using MouseMotionListener and paintComponent on a JPanel.
I don't know how to get the width and height of the rectangle but I've tried this it doesn't draw any rectangle:
I calculated the height and width according to the mousedragged point and mousereleased point.
Thanks
import java.awt.Point;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.*;
public class DrawRect extends JPanel
{
private int pointCount =0;
private int pointCount2 =0;
private Point points[] = new Point[100];
private Point points2[] = new Point[100];
public DrawRect()
{
addMouseMotionListener( new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent ev)
{
if (pointCount < points.length)
{
points[pointCount] = ev.getPoint();
pointCount++;
repaint();
}
}//end mouse drag
public void mouseReleased(MouseEvent ev)
{
if (pointCount2<points2.length)
{
points2[pointCount2]= ev.getPoint();
pointCount2++;
repaint();
}
}
}
);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i =0;i<pointCount;i++)
g.fillRect(points[i].x,points[i].y,points2[i].x - points[0].x,points2[i].y - points[0].y);
}
public static void main(String[] args) {
DrawRect test = new DrawRect();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}