Meaningless Drivel is fun!*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "MouseMotion event to draw a circle" Watch "MouseMotion event to draw a circle" New topic
Author

MouseMotion event to draw a circle

alaina peeler
Greenhorn

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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CirclePanel());
frame.pack();
frame.setVisible(true);
}
}
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();
addMouseListener(listener);
addMouseMotionListener(listener);
setBackground(Color.black);
setPrefferedSize(new Dimension (300,200));
}
public void paintComponent (Graphics page)
{
super.paintComponent(page); *****here is where i need some advice
page.setColor(Color.red)' ****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();
repaint();
}
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.

Layne


Java API Documentation
The Java Tutorial
 
jQuery in Action, 2nd edition
 
subject: MouseMotion event to draw a circle
 
Similar Threads
MouseListener
[newbie] The type MouseComponent must implement the inherited abstract method MouseMotionListener...
keeping the lines
MousePressed
Mouse events