|
Creating Commands
There are three simple steps to using commands.
Write the configuration fileThe following shows a simple xml configuration file for a command with the id of "my.command".
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE commands SYSTEM "commands.dtd">
<commands version="1.1.0">
<command id="my.command">
<face>
<text>My _Command</text>
<icon type="classpath">images/my-commands-icon.gif</icon>
<description>This will be in the tooltip</description>
<accelerator key="a">
<modifier value="control"/>
</accelerator>
</face>
</command>
</commands>
The <face> element is used to define the visual appearance of the buttons and menu items created by this command. Because only a single face is defined, it is used as the default for all buttons and menus this command creates (you can read a detailed explanation of faces here). The elements of the face are fairly self explanatory but the following is worth noting.
Load the ConfigurationNow the configuration has been written, we can load it into the CommandManager .
// load the xml command definition and initialize the manager.
File myCommandFile = new File("commands.xml");
try
{
CommandManager.defaultInstance().load(myCommandFile);
}
catch (LoadException e)
{
// oops
e.printStackTrace();
System.exit(1);
}
Creating a CommandCreating a command instance is as simple performing the following steps.
public class MyCommand
extends ActionCommand
{
public MyCommand
{
super("my.command");
}
public void handleExecute()
{
System.out.println("I've been executed");
}
}
The constructors call to super("my.command") initializes the command with the configuration specified in the xml file.
// create a new instance of the command. MyCommand myCommand = new MyCommand(); // and use it! AbstractButton button = myCommand.createButton(); JMenuItem menu = myCommand.createMenuItem();
Notes on Button TypesThe default ActionCommand.createButton() methods will return a JButton, however CommandGroups and ToggleCommand s will return a JToggleButton.
|