Eclipse GEF 开发之:当图形editor被更改时Enable "Save" action

原文链接:http://blog.csdn.net/zhmz1326/article/details/473159

如何在一个GEF editor被编辑了之后,使file菜单下的save action enable呢?(此editor继承自WorkbenchPart。)
一开始我想override一下isDirty()方法就可以了,比如根据CommandStack
    public boolean isDirty() {
        return getCommandStack().isDirty();
    }

但这样还不够,尽管CommandStack确实dirty了,save 还是灰的。

在Eclipse Forum上找到这样一段话:
If you are inheriting from WorkbenchPart, the class, then you should do firePropertyChange(IEditorPart.PROP_DIRTY) whenever the state of dirty changes, either from dirty to not dirty (i.e. after a save or saveAs), or from not dirty to dirty (i.e. after a change). This tells the workbench to enable or disable the Save. However SaveAs should always be enabled for a writable file, that has nothing to do with it being dirty.

If you are not inheriting from WorkbenchPart, then you will need to duplicate that code and do the firing yourself.

看来一定要在PROP_DIRTY改变的时候fire它。
我做了一下修改, 首先写一个自己的CommandStackListener。
        private CommandStackListener commandStackListener = new CommandStackListener() {
                public void commandStackChanged(EventObject event) {
                        firePropertyChange(PROP_DIRTY);
                }
        };
然后在configureGraphicalViewer 时,加给commandStack。
protected void configureGraphicalViewer() {
        。。。。。
        getCommandStack().addCommandStackListener(commandStackListener);
    }

别忘了在dispose时释放此listener。


测试了一下,save终于在dirty时变亮了。^_^

不过还是有一点问题,作一些修改,然后save 文件,然后undo到尽头,这时save变灰了,which shouldn't! 看来问题是出在isDirty上了, getCommandStack().isDirty() 上F3一下,发现一个saveLocation属性,下面还有一个markSaveLocation()。回到Editor, 在doSave()末尾修改:
        public void doSave(IProgressMonitor monitor) {
                。。。。。。
                getCommandStack().markSaveLocation();
    }

再测试一下,大功告成了。

你可能感兴趣的:(eclipse)