在此部分,我们将创建一个包含场景的单独的类。然后将其关联到我们的 JPanel 。
创建一个名为 GraphSceneImpl.java 的新类。
使其扩展 GraphScene。
使用 IDE 一侧的灯泡图标添加 import 语句和抽象方法。现在,您应看到如下所示的内容:
package vislibdemo;
import org.netbeans.api.visual.graph.GraphScene;
import org.netbeans.api.visual.widget.Widget;
public class GraphSceneImpl extends GraphScene {
@Override
protected Widget attachNodeWidget(String arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected Widget attachEdgeWidget(String arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected void attachEdgeSourceAnchor(String arg0, String arg1, String arg2) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected void attachEdgeTargetAnchor(String arg0, String arg1, String arg2) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
我们将使用三个 LayerWidget ,类似于 Swing 中的 JGlassPane 。在类的顶部对其进行声明:
private LayerWidget mainLayer;
private LayerWidget connectionLayer;
private LayerWidget interactionLayer;
创建一个构造函数,初始化您的 LayerWidget 并将它们添加到 Scene 中:
public GraphSceneImpl() {
mainLayer = new LayerWidget(this);
connectionLayer = new LayerWidget(this);
interactionLayer = new LayerWidget(this);
addChild(mainLayer);
addChild(connectionLayer);
addChild(interactionLayer);
}
接下来,定义创建新的小部件时发生的情况:
@Override
protected Widget attachNodeWidget(String arg) {
IconNodeWidget widget = new IconNodeWidget(this);
if (arg.startsWith("1")) {
widget.setImage(ImageUtilities.loadImage("vislibdemo/red.gif"));
} else if (arg.startsWith("2")) {
widget.setImage(ImageUtilities.loadImage("vislibdemo/green.gif"));
} else {
widget.setImage(ImageUtilities.loadImage("vislibdemo/blue.gif"));
}
widget.setLabel(arg);
mainLayer.addChild(widget);
return widget;
}
在场景中调用 addNode 时,即会触发以上语句。
在构造函数末尾,触发上面的方法 4 次:
Widget w1 = addNode("1. Hammer");
w1.setPreferredLocation(new Point(10, 100));
Widget w2 = addNode("2. Saw");
w2.setPreferredLocation(new Point(100, 250));
Widget w3 = addNode("Nail");
w3.setPreferredLocation(new Point(250, 250));
Widget w4 = addNode("Bolt");
w4.setPreferredLocation(new Point(250, 350));
在以上代码中,您创建了四个小部件,传递了一个字符串并且设置了小部件的位置。现在,触发上一步骤中定义的 attachNodeWidget 方法。 attachNodeWidget 中的 arg 参数是您传递到 addNode 的字符串。因此,此字符串将会设置小部件的标签。然后,会将该小部件添加到 mainLayer 中。
返回到 Main.java 类,将下面以粗体显示的行添加到 initComponents 方法中:
private void initComponents() {
//Set the layout:
setLayout(new BorderLayout());
//Create a JScrollPane:
JScrollPane scrollPane = new JScrollPane();
//Add the JScrollPane to the JPanel:
add(scrollPane, BorderLayout.CENTER);
*//Create the GraphSceneImpl:
GraphScene scene = new GraphSceneImpl();
//Add it to the JScrollPane:
scrollPane.setViewportView(scene.createView());
//Add the SatellitView to the scene:
add(scene.createSatelliteView(), BorderLayout.WEST);*
}
运行应用程序,您应看到如下所示的内容:
现在您有了一个包含一些小部件的场景,我们可以开始集成一些操作了!