Make And Move Circles
import java.awt.*;
class Circle
{
Color color;
int left, top;
int diameter;
Graphics graphics;
public Circle(int dia, int x, int y, Graphics g)
{
diameter = dia;
left = x;
top = y;
color = Color.blue;
graphics = g;
}
public void setColor(Color c) { color = c; }
public boolean find (int x, int y)
{
if (x > left && x < left+diameter &&
y > top && y < top+diameter) return true;
return false;
}
public void draw()
{
graphics.setColor(color);
graphics.fillOval(left,top,diameter,diameter);
}
public void drawBlank()
{
graphics.setColor(Color.white);
graphics.fillOval(left,top,diameter,diameter);
}
public void setXY(int x, int y)
{
left = x;
top = y;
}
public int getX() { return left; }
public int getY() { return top; }
}
class CircleDB
{
int index;
Circle circles[];
public CircleDB ()
{
circles = new Circle[100];
index = 0;
}
public void add (Circle c) { circles[index++] = c; }
public Circle top() { return circles[index-1]; }
public Circle find(int x, int y)
{
for (int i=index-1 ; i >= 0 ; i--)
if (circles[i].find(x,y)) return circles[i];
return null;
}
public void draw ()
{
for (int i=0 ; i < index ; i++) circles[i].draw();
}
}
public class CirclesMove extends Frame
{
Button circle, red, green, blue;
CircleDB cdb;
Canvas drawArea;
Circle gotit = null;
int xdiff, ydiff;
Graphics g;
public CirclesMove ()
{
cdb = new CircleDB();
setLayout(new BorderLayout());
Panel p = new Panel();
p.setLayout(new GridLayout(16,1));
p.add(circle = new Button("Circle"));
p.add(new Label(""));
p.add(red = new Button("Red"));
p.add(green = new Button("Green"));
p.add(blue = new Button("Blue"));
add ("East", p);
drawArea = new Canvas();
drawArea.setBackground(Color.white);
g = drawArea.getGraphics();
add ("Center", drawArea);
}
public boolean action(Event evt, Object obj)
{
if (evt.target.equals(circle))
cdb.add(new Circle(50,100,100,drawArea.getGraphics()));
else
if (evt.target.equals(red))
cdb.top().setColor(Color.red);
else
if (evt.target.equals(green))
cdb.top().setColor(Color.green);
else
if (evt.target.equals(blue))
cdb.top().setColor(Color.blue);
cdb.draw();
return super.action(evt,obj);
}
public boolean mouseDown(Event evt, int x, int y)
{
gotit = cdb.find(x,y);
if (gotit == null) return true;
xdiff = x - gotit.getX();
ydiff = y - gotit.getY();
return true;
}
public boolean mouseDrag(Event evt, int x, int y)
{
if (gotit == null) return true;
gotit.drawBlank();
gotit.setXY(x-xdiff, y-ydiff);
cdb.draw();
return true;
}
public boolean mouseUp (Event evt, int x, int y)
{
gotit = null;
return true;
}
public static void main (String arg[])
{
CirclesMove c = new CirclesMove();
c.resize(500,400);
c.show();
}
}