意指在图形上直接修改,直接响应。
按照GEF的开发思路。
1.显然我们要提供这样一种直接编辑的策略,然后将其安装到相应EditPart上。
该策略继承自DirectEditPolicy即可。
我们覆盖其抽象方法getDirectEditCommand(DirectEditRequest request)就可以了。
方法原型为:
protected abstract Command getDirectEditCommand(DirectEditRequest request);
2.将此策略安装到相应的EditPart上。
eg:
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new AppDirectEditPolicy());
3.如何响应Direct Edit?
涉及EditPart的一个方法void performRequest(Request request);
并不是所有的Request都交给getCommand函数处理,有些Request也直接分派给EditPart自己处理(performRequest方法处理)。
performRequest方法用于处理一些特殊的请求。
它让EditPart去do something,可能是一些并不会立即就改变model的改变,比如打开对话框或者激活直接编辑模式。
一个经常的应用是Direct Edit
//这个用于处理一些特殊的请求(Request),比如Direct Edit
@Override
public void performRequest(Request req) {
if (req.getType().equals(RequestConstants.REQ_DIRECT_EDIT)
|| req.getType().equals(RequestConstants.REQ_OPEN)) {
//do something 比如显示直接编辑框
if (directManager == null) {
directManager = new NoteDirectEditManager();
}
directManager.show();//显示CellEditor
}
super.performRequest(req);
}
4.到这里我们已经能够响应直接编辑请求了。接下来的问题是我们要显示一种直接编辑的控件,比如文本框,并指定其弹出位置。这个GEF也有相应的接口让我们去实现。
DirectEditManager类。
eg:
private class NoteDirectEditManager extends DirectEditManager {
public NoteDirectEditManager() {
super(NoteEditPart.this, MultiLineCellEditor.class,
new NoteCellEditorLocator());
}
protected void initCellEditor() {
getCellEditor().setValue(((NoteModel) getModel()).getContent());
Text text = (Text) getCellEditor().getControl();
text.selectAll();
}
}
其中MultiLineCellEditor是CellEditor的子类,我们可以任意去实现自己的CellEditor。
控制CellEditor显示位置的类一般继承自CellEditorLocator。
eg:
/**
* CellEditorLocator
*/
private class NoteCellEditorLocator implements CellEditorLocator {
public void relocate(CellEditor celleditor) {
IFigure figure = getFigure();
Text text = (Text) celleditor.getControl();
Rectangle rect = figure.getBounds().getCopy();
figure.translateToAbsolute(rect);
text.setBounds(rect.x + 5, rect.y + 5, rect.width - 5,
rect.height - 5);
}
}
5.到现在为止,直接编辑可以响应了,也可以弹出编辑框了。
接下来要做的就是修改模型。修改模型涉及到Command。
我们定义一个Command就是。将CellEditor中设置的值通过Command持久到模型上去就行了。
6.还有事情没做吗?
也许。模型修改了是否有刷新视图。这个当然也是由EditPart做的。我们去实现就是了。