wearybands wearybands - 7 months ago 31
Java Question

Apply and OK Button in Eclipse PreferencePage

What is the standard and recommended way the apply and ok button in eclipse preference page should work.

I checked and found that performOK() method is called when we click apply or ok button. It means if I have some computations or let say thread starting on in performOK() and the user first click on apply and then ok button it will be executed twice and if the user clicks on apply and cancel the changes will be applied anyways?

Is there a way to not execute the code twice if the user clicks on apply and then ok ?

@Override
protected void performApply() {
this.performOk();
}

@Override
public boolean performOk() {
PreferencesUtil.savePreferences();
return super.performOk();
}


Thanks

Answer Source

It is up to you to remember that Apply has been run by overriding performApply and setting a flag. You can then test the flag in performOk and skip doing the same thing.

Be sure to clear the flag if the user changes something after pressing Apply.

So something like:

private boolean saveDone = false;


public boolean performOk() {

  if (!saveDone) {
    saveDone = true;

    store.setValue(Constants.ENABLE_DEFAULT_COLOR, this.defaultColoringCheckBox.getSelection());
    PreferencesUtil.addToPreferenceStore(viewer.getTable());
    PreferencesUtil.savePreferences();
  }

  return super.performOk();
}

Set saveDone = false if anything is changed in the page.