public class Connection {
static String layer1 = "layer1";
static String layer2 = "layer2";
public static void main(String args[]) {
Shell shell = new Shell();
shell.setSize(350, 350);
shell.open();
shell.setText("Connection Demo");
LightweightSystem lws = new LightweightSystem(shell);
LayeredPane manager = new LayeredPane();
lws.setContents(manager);
IFigure panel = new Layer();
panel.setOpaque(false);
manager.add(panel, layer1, -1);
IFigure conLayer = new Layer();
conLayer.setOpaque(false);
manager.add(conLayer, layer2, -1);
RectangleFigure node1 = new RectangleFigure(), node2 = new RectangleFigure();
node1.setBackgroundColor(ColorConstants.red);
node1.setBounds(new Rectangle(30, 30, 64, 36));
RectangleFigure node3 = new RectangleFigure();
node3.setBounds(new Rectangle(100, 100, 64, 36));
node2.setBackgroundColor(ColorConstants.blue);
node2.setBounds(new Rectangle(200, 200, 64, 36));
PolylineConnection conn = new PolylineConnection();
conn.setSourceAnchor(new ChopboxAnchor(node1));
conn.setTargetAnchor(new ChopboxAnchor(node2));
conn.setTargetDecoration(new PolygonDecoration());
// conn.setConnectionRouter(new ManhattanConnectionRouter());
conn.setConnectionRouter(new ShortestPathConnectionRouter(panel));
Label label = new Label("Midpoint");
label.setOpaque(true);
label.setBackgroundColor(ColorConstants.buttonLightest);
label.setBorder(new LineBorder());
// 添加连线的Locator
conn.add(label, new MidpointLocator(conn, 0));
// 在底层Figure中添加子Figure
panel.add(node1);
panel.add(node2);
panel.add(node3);
conLayer.add(conn);
new Dragger(node1);
new Dragger(node2);
new Dragger(node3);
Display display = Display.getDefault();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
static class Dragger extends MouseMotionListener.Stub implements MouseListener{
private Point last;
public Dragger(IFigure figure){
figure.addMouseMotionListener(this);
figure.addMouseListener(this);
}
public void mouseDoubleClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
last = e.getLocation();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point p = e.getLocation();
Dimension delta = p.getDifference(last);
last = p;
Figure f = (Figure) e.getSource();
//设置拖动的Figure的位置
f.setBounds(f.getBounds().getTranslated(delta.width,delta.height));
}
}
}
使用 ShortestPathConnectionRouter需要使用多层次。这个使用了两层,一层是放置的node,一层放置的是连线。