Having looked at menu items with check boxes yesterday, let’s look at another kind of action today: combo boxes.
The most prominent example of a combo box action in MPS or IDEA is the toolbar action that lets you choose a run configuration:
Implementing such an action in MPS again requires us to descend to the Java level because there are no ready-made DSL
constructs for combo box actions in the plugin language. We need to extend the
com.intellij.openapi.actionSystem.ex.ComboBoxAction
class and implement one abstract method,
createPopupActionGroup(JComponent component)
. A sample implementation could look like this:
@NotNull()
@Override
protected DefaultActionGroup createPopupActionGroup(JComponent component) {
// Can use the component parameter with DataManager to obtain
// context parameters. Example:
// MPSDataKeys.MPS_PROJECT.getData(
// DataManager.getInstance().getDataContext(component));
return new DefaultActionGroup(
new ToggleActionExample(1),
new ToggleActionExample(2),
new ToggleActionExample(3));
}
The DefaultActionGroup
that we return is created dynamically in the example above, but we could also return an
existing group defined in the plugin language using the actiongroup
expression:
return actionGroup < ToggleActions >;
To add our new combo box to the main tool bar we need to create another action group, similarly to the way we did it in yesterday’s post:
If we now build our project, we end up with a combo box on the main toolbar that looks like this:
Almost there! How do we give the button a text? The easiest way would have been to invoke a constructor with a String text
parameter, except that ComboBoxAction
doesn’t provide one. Instead, we can set the text in the constructor via
the template presentation:
public ComboBoxActionExample() {
getTemplatePresentation().setText("Example Combo Box Action");
}
And now it looks better:
How can we set the combo box text dynamically? To do that, we need to override the update(AnActionEvent)
method and
write the necessary code to update the presentation:
@Override
public void update(@NotNull() AnActionEvent e) {
e.getPresentation().setText("Dynamically updated text");
}
If you want to see the code in action, I have updated the sample project on GitHub.