File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes MouseMotion event to draw a circle Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "MouseMotion event to draw a circle" Watch "MouseMotion event to draw a circle" New topic

MouseMotion event to draw a circle

alaina peeler

Joined: Dec 04, 2005
Posts: 29
Ok i am supposed to write a program that draws a circle in which it's size is determined by a mouse drag. The initial click of the mouse will be the center point for my circle. Im supposed to compute the distance between the current location of the mouse pointer and the center point to determine the current radius. I don't exactly know where to compute that. This is what i have so far

import javax.swing.JFrame;
public class Circle
public static void main(String[] args);
{ JFrame frame = new JFrame("Circle");
frame.getContentPane().add(new CirclePanel());
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CirclePanel extends JPanel
{ private int size;
private Point point1, point2;

public CirclePanel();
{ pointList = new ArrayList<Point>();
CircleListener listener = new CircleListener();
setPrefferedSize(new Dimension (300,200));
public void paintComponent (Graphics page)
super.paintComponent(page); *****here is where i need some advice
page.setColor(' ****i think it's in this method i need to
***calculate the distance from the previous
**point to the current point to find my radius
*and draw the circle
public class CircleListener implements MouseListener, MouseMotionListener
public void mousePressed(MouseEvent event)
{ point1 = event.getPoint();
public void mouseDragged(MouseEvent event)
{ point2 = event.getPoint();
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I think the comments in your code have the right idea. Since you need the radius before you draw the circle, you can calculate it in painComponent() just before you draw the circle. Alternatively, you could calculate the radius in mouseDragged() and store it as a member variable rather than storing the position of the mouse. This is a good example of TIMTOWTDI (there is more than one way to do it), since either way will work just fine.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: MouseMotion event to draw a circle
It's not a secret anymore!