使用swt实现两个树之间节点上点击绘制连线
时间: 2023-07-20 12:19:20 浏览: 170
两个节点之间画线,使用SVG,案例建议使用webstorm打开,就不用自己另外启一个服务了
以下是使用 Eclipse SWT 实现在两个树之间绘制连线的示例代码:
```java
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class TreeLinkExample {
private static TreeItem sourceItem = null;
private static TreeItem targetItem = null;
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Tree tree1 = new Tree(shell, SWT.BORDER);
for (int i = 0; i < 5; i++) {
TreeItem item = new TreeItem(tree1, SWT.NONE);
item.setText("Item " + i);
}
Tree tree2 = new Tree(shell, SWT.BORDER);
for (int i = 0; i < 5; i++) {
TreeItem item = new TreeItem(tree2, SWT.NONE);
item.setText("Item " + i);
}
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
if (sourceItem != null && targetItem != null) {
GC gc = e.gc;
Rectangle sourceBounds = sourceItem.getBounds();
Rectangle targetBounds = targetItem.getBounds();
Point sourceCenter = new Point(sourceBounds.x + sourceBounds.width / 2,
sourceBounds.y + sourceBounds.height / 2);
Point targetCenter = new Point(targetBounds.x + targetBounds.width / 2,
targetBounds.y + targetBounds.height / 2);
gc.setLineWidth(2);
gc.setForeground(new Color(e.display, 0, 0, 255));
gc.drawLine(sourceCenter.x, sourceCenter.y, targetCenter.x, targetCenter.y);
}
}
});
tree1.addListener(SWT.Selection, event -> {
sourceItem = (TreeItem) event.item;
redrawCanvas(canvas);
});
tree2.addListener(SWT.Selection, event -> {
targetItem = (TreeItem) event.item;
redrawCanvas(canvas);
});
shell.setSize(400, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private static void redrawCanvas(Canvas canvas) {
canvas.redraw();
canvas.update();
}
}
```
这个示例程序创建了两个树控件和一个 `Canvas` 控件,并在树控件上添加了 `Selection` 监听器,在监听器中记录了选中的项。同时,在 `Canvas` 上添加了 `PaintListener`,在监听器中根据选中的两个树项绘制了一条连接线。当有树项被选中时,先记录下来,然后调用 `redrawCanvas` 方法重绘 `Canvas` 控件。
阅读全文