import java.awt.event.*;
import java.awt.*;
import javax.swing.JPanel;
import java.util.ArrayList;
import java.util.Random;
public class OctagonPanel extends JPanel
{
private Octagon octagon;
private Octagon selectedOctagon = null;
private ArrayList<Octagon> lstOctagon = new ArrayList<Octagon>();
static Random generator = new Random();
int oldx, oldy, difx, dify, newx, newy;
public OctagonPanel()
{
addMouseListener(new OctagonsListener());
addMouseMotionListener(new OctagonsListener());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); //optional here
for(Octagon o : lstOctagon)
{
o.draw(g);
}
}
private class OctagonsListener implements MouseListener, MouseMotionListener
{
int n;
private Octagon hitTest(MouseEvent e)
{
Octagon hitO = null;
for (Octagon o : lstOctagon)
{
if (o.contains(e.getX(), e.getY()))
{
hitO = o;
break;
}
}
return hitO;
}
public void mousePressed (MouseEvent e)
{
selectedOctagon = hitTest(e); pressedX = e.getX();pressedY = e.getY();
}
public void mouseClicked(MouseEvent e)
{
oldx = e.getX();
oldy = e.getY();
if(selectedOctagon == null)
{
System.out.println(oldx);
n = generator.nextInt(50);
int[]x = {oldx, oldx + n, oldx + n, oldx, oldx - 2*n, oldx - 3*n, oldx - 3*n, oldx - 2*n};
int[]y = {oldy, oldy + n, oldy + 2*n, oldy + 3*n, oldy + 3*n, oldy + 2*n, oldy + n, oldy};
octagon = new Octagon(x, y, 8);
lstOctagon.add(octagon);
repaint();
}
}
public void mouseReleased(MouseEvent e)
{
//selectedOctagon = null;
repaint();
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
newx = e.getX(); newy = e.getY();
if(selectedOctagon != null)
{
difx = newx - pressedX; dify = newy - pressedY;
selectedOctagon.translate(difx, dify);
repaint();
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
}