How to fix this code to move this shape?
Hi guys
Below code can draw a polygon whenever the mouse is pressed, but it is also supposed to drag the polygon to move to anywhere the mouse is released. But the polygon doesn't move at all.
Does anyone know how to fix it?
I believe it must be something wrong in OctagonPanel class, please see my OctagonPanel class below:
(public class Octagon extends Polygon {....} and public class Main {...} are omitted here.)
Code:
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, newx, newy;
boolean dragging = false;
public OctagonPanel()
{
addMouseListener (new OctagonsListener());
addMouseMotionListener (new OctagonsListener());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(Octagon o : lstOctagon)
{
o.draw(g);
}
}
private class OctagonsListener implements MouseListener, MouseMotionListener
{
public void mousePressed (MouseEvent e)
{
oldx = e.getX();
oldy = e.getY();
for(Octagon o : lstOctagon)
{
if(o.contains(oldx, oldy))
{
selectedOctagon = o;
dragging = true;
}
}
if(selectedOctagon == null)
{
int n = generator.nextInt(80);
int[] newx = {oldx, oldx + n, oldx + n, oldx, oldx - 2*n, oldx - 3*n, oldx - 3*n, oldx - 2*n};
int[] newy = {oldy, oldy + n, oldy + 2*n, oldy + 3*n, oldy + 3*n, oldy + 2*n, oldy + n, oldy};
octagon = new Octagon(newx, newy, 8);
lstOctagon.add(octagon);
repaint();
}
}
public void mouseReleased(MouseEvent e)
{
if(dragging = true)
{
repaint();
}
selectedOctagon = null;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e) {}
public void mouseDragged(MouseEvent e)
{
newx = e.getX();
newy = e.getY();
int xtrans = newx - oldx;
int ytrans = newy - oldy;
selectedOctagon.translate(xtrans,ytrans);
repaint();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
}
Thanks heaps