[Eclipse]处理颜色类型的偏好项
在Eclipse里实现偏好页(PreferencePages)时,我们一般要在Plugin类的start()方法里预先设置好每一项的缺省值,但IPreferenceStore接口只提供了参数为整型、布尔型、字符串等基本类型的setDefault()方法,如果某个偏好项是颜色类型怎么办呢?
这时要使用PreferenceConverter这个类,也是由jface提供的,该类提供了额外的一些setDefault()方法可以接收RGB、Font、Point等类型的参数,所以可以使用下面的方法设置缺省值:

要取得某个颜色类型的偏好项值,就用下面的语句:

JFace在颜色、图象和字体等资源的管理方面为我们做了很多工作,我们应该尽量利用已有的这些功能。
图1 颜色类型的偏好项
顺便说一下,要让editor里的图形在用户更改preference设置后立即反应变化,要在preferenceStore上增加监听器,例如在editor的initializeGraphicalViewer()方法里这样写:
protected void initializeGraphicalViewer() {

Activator.getDefault().getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
//You may refresh some editparts only for better performance
// if(IConstants.PREF_SHOW_ACTIVITIES.equals(event.getProperty()))
refreshAllEditParts(getGraphicalViewer().getRootEditPart());
}
private void refreshAllEditParts(EditPart part) {
part.refresh();
List children = part.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) {
EditPart child = (EditPart) iter.next();
refreshAllEditParts(child);
}
}
});
}

Activator.getDefault().getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
//You may refresh some editparts only for better performance
// if(IConstants.PREF_SHOW_ACTIVITIES.equals(event.getProperty()))
refreshAllEditParts(getGraphicalViewer().getRootEditPart());
}
private void refreshAllEditParts(EditPart part) {
part.refresh();
List children = part.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) {
EditPart child = (EditPart) iter.next();
refreshAllEditParts(child);
}
}
});
}
最后,org.eclipse.ui.preferencePages扩展点的page元素的category属性的值应该是另一个page的id值。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步