toggle me

If you want to add toggle menu options ie. menu optoin with check mark, here is how can you do it:

Commands can have states associated with it. A state id known by its id and it can have any value, which is stored in a subclass of org.eclipse.core.commands.State. To know whether a command is checked or not, the Command Framework looks for a state with the id 'org.eclipse.ui.commands.toggleState'. Lets specify the default checked state of Bold to true and Italic to false:


< command
defaultHandler="com.eclipse_tips.commandstate.BoldHandler"
id="com.eclipse-tips.commandState.boldCommand"
name="Bold">
< state
class="org.eclipse.ui.handlers.RegistryToggleState:true"
id="org.eclipse.ui.commands.toggleState">
< /state>
< /command>
< command
defaultHandler="com.eclipse_tips.commandstate.ItalicHandler"
id="com.eclipse-tips.commandState.italicCommand"
name="Italic">
< state
class="org.eclipse.ui.handlers.RegistryToggleState:false"
id="org.eclipse.ui.commands.toggleState">
< /state>
< /command>


The Framework expects a Boolean value from the state. It doesn't care about which class that holds the state. So why should we use the RegistryToggleState instead of our own state class? Two reasons:

It implements IExecutableExtension. So you can specify the default values in the plugin.xml as I've done above.
It extends PersistentState, so it can remember the value between Eclipse sessions.
So if the user had checked/unchecked the menu, restarts Eclipse, he will get the same state as he left before - all this, you get without even your plugin being loaded.
So how should the handler work for this command?

public Object execute(ExecutionEvent event) throws ExecutionException
{
Command command = event.getCommand();
boolean oldValue = HandlerUtil.toggleCommandState(command);
// use the old value and perform the operation
return null;
}


Basically, its the Handler's responsibility to update the Command's state. The HandlerUtil has a convenient method which toggles the state and gives you the old value of the state. You can use the value to perform the operation.

To know more about Radio style menu optoins :

http://blog.eclipse-tips.com/2009/03/commands-part-6-toggle-radio-menu.html

Eclipse Resources


Eclipse Platform Technical OverView, JDT Tooling Support and features