Thursday 4 October 2007

Dynamic Palettes in GEF

Hello again, I am finally back from holiday. Today I will describe a short trick for dynamically updating your GEF Palette.
I wanted to change the contents of the palette in graphical editor depending on user's choice in one of the combo boxes. Imagine combining two models into one by giving user a choice which one to use.

The original palette is usually created on graphical editor initialisation. You, however, can change the contents of this palette dynamically by modifying the PaletteRoot of your graphical editor.

So, I have created an additional method in my graphical editor:

public void updatePalette(LogicalModel model) {
PaletteRoot root = getPaletteRoot();
List children = root.getChildren();
for (int i = 0; i < children.size(); i++) {
if (children.get(i) instanceof PaletteGroup) {
PaletteGroup entry = (PaletteGroup) children.get(i);
if (entry.getLabel().equals("Plots")) {
// This is a group we want to update
List plots = model.getPlots();
int size = entry.getChildren().size();
for (int j = 0; j < size; j++) {
entry.getChildren().remove(0);
}
for (int j = 0; j < plots.size(); j++) {
CombinedTemplateCreationEntry component = new CombinedTemplateCreationEntry(plots.get(j).getName(), plots.get(j).getName(),
Plot.class, new SimpleFactory(Plot.class), ImageDescriptor.createFromFile(ResultsEditor.class,
"icons/plot.gif"), ImageDescriptor.createFromFile(ResultsEditor.class, "icons/plot.gif"));
entry.add(component);
}
}
}
}
}

This method flushes the whole content of the palette group named "Plots", and recreates it from some logical model.
All I have to do now is to call this new method from an appropriate listener to combo's selection change.