java调用FieldEditor#setEnabled时要设置什么父级?
通过扩展FieldEditorReferencePage类,我正在Eclipse中构建一个首选项页面。此页面包含2个字段:1个BooleanFieldEditor(复选框)和1个FileFieldEditor。我想禁用/启用复选框值后面的文件字段。 我找到了类似的东西(一些明显的代码没有显示):
public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
public static final String PREF_KEY_1 = "checkBoxPref";
public static final String PREF_KEY_2 = "filePref";
private FileFieldEditor pathField;
private BooleanFieldEditor yesOrNoField;
private Composite pathFieldParent;
@Override
protected void createFieldEditors() {
this.yesOrNoField = new BooleanFieldEditor(PREF_KEY_1, "Check this box!", getFieldEditorParent());
this.pathFieldParent = getFieldEditorParent();
this.pathField = new FileFieldEditor(PREF_KEY_2, "Path:", this.pathFieldParent);
addField(this.yesOrNoField);
addField(this.pathField);
boolean isChecked = getPreferenceStore().getBoolean(PREF_KEY_1);
updatePathFieldEnablement(! isChecked);
}
/**
* Updates the fields according to entered values
*/
private void updatePathFieldEnablement(boolean enabled) {
this.pathField.setEnabled(enabled, this.pathFieldParent);
}
@SuppressWarnings("boxing")
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(FieldEditor.VALUE) && event.getSource() == this.yesOrNoField) {
updatePathFieldEnablement(! (boolean) event.getNewValue());
}
super.propertyChange(event);
}
}
我的问题是关于FieldEditor#setEnabled中的第二个参数。这个参数是FieldEditor控件的父组合(“用于创建需要的控件”,javadoc说)。起初,我通过返回getFieldEditorParent来设置该值,但随后出现了一个异常“不同的父级”。所以我结束了对它的存储(参见this.pathFieldParent),并将其返回给setEnabled,然后它就工作了(或者似乎工作了)。 但我不确定我是否做得很好,尤其是因为我必须在我的类中创建一个对它来说毫无意义的成员(如果我有许多字段要启用/禁用,我将不得不创建其中许多)
你认为我做得好吗,还是有更好的方式来提供这个父母?你能解释一下为什么“setEnabled”需要它吗
谢谢
# 1 楼答案
您正在使用首选项页面的默认
FLAT
布局。使用此布局时,对getFieldEditorParent
的每次调用都会生成一个新的组合,因此您只需进行一次调用,并记住正确的父级。使用GRID
布局getFieldEditorParent
总是返回相同的父级。这是实际代码:setEnabled
有时会创建一个新的Label
控件,因此它需要知道正确的父组合