GUI Commands 2.0 has arrived! Find out what's new and improved.
Creating Commands

There are three simple steps to using commands.

  1. Create and xml file describing the command properties.
  2. Load the xml file into the CommandManager
  3. Create a subclass of ActionCommand and implement its handleExecute() method.

Write the configuration file

The 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.

  • The accelerator is only used by menus. Further information regarding accelerator configuration can be found in command faces.
  • Multiple <modifier> elements can be specified.

Load the Configuration

Now 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 Command

Creating 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 Types

The default ActionCommand.createButton() methods will return a JButton, however CommandGroups and ToggleCommand s will return a JToggleButton.