二、建立連接配接模型
建立連接配接模型,過程大同小異。此時需要在結點模型上安裝Policy,Policy的類型為:GraphicalNodeEditPolicy。
在HelloWorldEditPart的createEditPolicies()方法裡追加:
installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, new HelloWorldGraphicalNodeEditPolicy());
其中HelloWorldGraphicalNodeEditPolicy是我們的Policy實作類。還是一樣,先完成Command,再回過頭來完成Policy。
要成功的實作一個連接配接,首先我們知道至少需要有三個對象:連接配接線、源結點和目标結點。是以我們的command的可以如下實作: 這時顯示出來的效果和上一節一樣:能建立,不顯示。還是因為沒重新整理的問題。增加一個重新整理事監聽即可。如下:
public class AddConnectionCommand extends Command {
private AbstractConnectionModel connection;
public AddConnectionCommand(AbstractConnectionModel connection) {
super();
this.connection = connection;
}
public void setSrc(HelloWorldModel src) {
connection.setSrc(src);
}
public void setTarget(HelloWorldModel target) {
connection.setTarget(target);
}
public void setConnection(AbstractConnectionModel connection) {
this.connection = connection;
}
@Override
public void execute() {
connection.attachSource();
connection.attachTarget();
}
@Override
public void undo() {
connection.deattachTarget();
connection.deattachSource();
}
}
然後我們實作我們的Policy。這裡要分兩步進行,首先是完成源結點的連接配接,然後就完成目标結點的連接配接,代碼如下:
@Override
protected Command getConnectionCompleteCommand(
CreateConnectionRequest request) {
AddConnectionCommand command = (AddConnectionCommand) request
.getStartCommand();
command.setTarget((HelloWorldModel) getHost().getModel());
return command;
}
@Override
protected Command getConnectionCreateCommand(CreateConnectionRequest request) {
AddConnectionCommand command = new AddConnectionCommand(
(AbstractConnectionModel) request.getNewObject());
command.setSrc((HelloWorldModel) getHost().getModel());
request.setStartCommand(command);
return command;
}
修改HelloWorldModel裡與連接配接相關的四個方法如下:
public static final String P_SOURCE = "p_source";
public static final String P_TARGET = "p_target";
public void addInput(AbstractConnectionModel model) {
if (!inputs.contains(model)) {
inputs.add(model);
firePropertyChange(P_TARGET, null, model);
}
}
public void addOut(AbstractConnectionModel model) {
if (!outputs.contains(model)) {
outputs.add(model);
firePropertyChange(P_SOURCE, null, model);
}
}
public void removeInput(AbstractConnectionModel model) {
if (inputs.contains(model)) {
inputs.remove(model);
firePropertyChange(P_TARGET, model, null);
}
}
public void removeOut(AbstractConnectionModel model) {
if (outputs.contains(model)) {
outputs.remove(model);
firePropertyChange(P_SOURCE, model, null);
}
}
然後再修改對應的EditPart的propertyChange()方法如下:
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals(HelloWorldModel.P_CONSTRAINT)){
refreshVisuals();
}else if(evt.getPropertyName().equals(HelloWorldModel.P_SOURCE)){
refreshSourceConnections();
}else if(evt.getPropertyName().equals(HelloWorldModel.P_TARGET)){
refreshTargetConnections();
}
}
最後試一下效果:
圖三
小提示:EditPolicy的getHost()方法傳回的是安裝這個Policy的那個對象。也就是安裝這個Policy的那個EditPart。