package com.jedics.graph.visual;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.SwingUtilities;
import com.jedics.graph.GraphHandler;
public class VertexMouseHandler extends MouseAdapter implements MouseMotionListener {
/**
* To Enable generic dragging. Can be static because only one drag can take place at a time.
*/
private static Point start;
/**
* To allow edge updates while dragging. Can be static because only one drag can take place at a time.
*/
private static boolean dragTempEdge;
static {
start = null;
dragTempEdge = false;
}
private GraphHandler handler;
private GraphCanvas canvas;
private VertexComponent v;
private TempEdgeComponent t;
public VertexMouseHandler(GraphHandler handler, GraphCanvas canvas) {
this.handler = handler;
this.canvas = canvas;
}
@Override
public void mousePressed(MouseEvent e) {
v = (VertexComponent)e.getComponent();
v.changing = true;
if(e.getClickCount() >= 2) {
if(e.getButton() == MouseEvent.BUTTON1) {
dragTempEdge = true;
addTempEdge(v);
} else if(e.getButton() == MouseEvent.BUTTON3) {
v.removeMouseListener(this);
v.removeMouseMotionListener(this);
handler.removeVertex(v.getId());
}
} else if(e.getButton() == MouseEvent.BUTTON1) {
start = e.getPoint();
handler.fireVertexSelected(v.getId());
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(start != null) {
v.setLocation(v.getX() + e.getX() - start.x, v.getY() + e.getY() - start.y);
canvas.repaint();
}
if(dragTempEdge) {
Point p = e.getPoint();
p.translate(v.getX(), v.getY());
updateTempEdge(p);
}
}
@Override
public void mouseReleased(MouseEvent e) {
v.changing = false;
v.fireVertexLocationChanged();
start = null;
if(dragTempEdge) {
Point p = e.getPoint();
p.translate(v.getX(), v.getY());
releaseTempEdge();
dragTempEdge = false;
}
}
private void releaseTempEdge() {
canvas.remove(t);
if(!t.isValid()) {
canvas.repaint();
return;
}
canvas.createEdge(t.u.getId(), t.v.getId());
t = null;
}
protected void addTempEdge(VertexComponent v) {
t = new TempEdgeComponent(v);
t.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
canvas.add(t, 997);
}
protected void updateTempEdge(Point p) {
if(t != null) {
Object o = SwingUtilities.getDeepestComponentAt(canvas, p.x, p.y);
if(o instanceof TempEdgeComponent) {
t.updateEnd(p);
} else if(o instanceof VertexComponent) {
t.updateEnd((VertexComponent)o);
} else {
o = SwingUtilities.getAncestorOfClass(VertexComponent.class, ((Component)o));
if(o instanceof VertexComponent) {
t.updateEnd((VertexComponent)o);
} else {
t.updateEnd(p);
}
}
}
canvas.repaint();
}
}