在属性页中,我们提供了文本编辑器,Combo编辑器,还有Color编辑器,但是对话框的编辑器只有一个抽象类DialogCellEditor。下面我们来实现一个在属性页中打开文件对话框的功能:
效果如图显示:
当点击树图的按钮时,弹出文件选择对话框,在eclipse 以及gef 的包中,没有关于FileDialogPropertyDescriptor 之类的定义,要实现这个功能需要我们自己去实现。
有两个比较关键的类:PropertyDescriptor 、DialogCellEditor ,我们需要分别继承这两个类。DialogCellEditor 是jface 包里的一个抽象类文件,它是用dialog 实现了一个cell 编辑器。这类编辑器通常是左边有个label 或在右边有个button ,单击这个button 会弹出一个对话框窗体(如color 对话框,file 对话框等)去改变cell editor 的值。
继承DialogCellEditor 的子类需要实现以下三个方法:
createButton: 创建cell editor 的button 控件
openDialogBox: 当点击button 时,打开对话框(我们需要在这里实现打开什么对话框)
updateLabel: 修改 cell editor 的label ,当它的值被改变。
我们实现的方法如下:
package com.jctx.dnrm.gef.model;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import com.jctx.dnrm.LogicPlugin;
public class FileDialogCellEditor extends DialogCellEditor {
public FileDialogCellEditor(Composite parent){
super(parent);
}
protected Object openDialogBox(Control cellEditorWindow) {
FileDialog fileDialog = new FileDialog(cellEditorWindow.getShell(),SWT.OPEN);
fileDialog.setFileName(" 选择图形文件");
fileDialog.setFilterExtensions(new String[]{"*.gif"});
//fileDialog.setFilterPath(getURLPath(LogicPlugin.class,"icons/gef/model"));
fileDialog.setFilterPath(getURLPath(LogicPlugin.class,"icons/gef/model"));
String path = fileDialog.open();
return path;
}
protected Button createButton(Composite parent){
Button result = new Button(parent, SWT.PUSH);
result.setText("..."); //$NON-NLS-1$
return result;
}
protected static String getURLPath(Class rsrcClass, String name){
return rsrcClass.getResource(name).getPath();
}
}
大家,注意OpenDialogBox这个方法,是在这里打开的对话框。在这个方法中,我还可以通过String value = (String) getValue();来获取当前的属性值。
另外,我们需要继承一个PropertyDescriptor ,命名为FileDialogPropertyDescriptor ,在这个类中来定义FileDialogCellEditor ,用来描述文件选择类的属性。子类需要重新实现一个getPropertyEditor 方法,来提供一个cell editor ,用来改变属性值。系统已经定义了以下三个:
1 )TextPropertyDescriptor – 编辑文本用 TextCellEditor
2 )ComboBoxPropertyDescriptor – 编辑下拉框 ComboBoxCellEditor
3 )ColorPropertyDescriptor – 编辑颜色Editor 用ColorCellEditor
我的FileDialogCellEditor 实现如下:
public class FileDialogPropertyDescriptor extends PropertyDescriptor {
public FileDialogPropertyDescriptor(Object id, String displayName) {
super(id, displayName);
}
public CellEditor createPropertyEditor(Composite parent) {
CellEditor editor = new FileDialogCellEditor(parent);
if (getValidator() != null)
editor.setValidator(getValidator());
return editor;
}
}
在IPropertyDescriptor[] 中加入new FileDialogPropertyDescriptor(PROP_ICONNAME," 树图") 就可以完成我们的需求了。