How to use CommandMenu

Please note: This article was previously posted on my weblog Tommis Swing Musings. I started that blog with high hopes, but due to a lack of time I decided to cancel Tommis Swing Musings. I have deleted that blog.

In my previous post I introduced you to a component called CommandMenu. Since the class itself is rather small, one might expect that using it could mean having to write lots of code. As you shall see shortly, this is not the case.

First, we need some instance variables:

// the content pane
private final JPanel contentPane;

// the command area
private final CommandMenu commandMenu;

// the module area
private final JScrollPane moduleScrollPane;

Here is how to set them up:

// the module area
moduleScrollPane = new JScrollPane();
// the command area
commandMenu = new CommandMenu();
// the content pane
contentPane = new JPanel(new BorderLayout(20, 0));
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.add(commandMenu, BorderLayout.WEST);
contentPane.add(moduleScrollPane, BorderLayout.CENTER);

So, the basic thing is to create some sort of content pane (contentPane) which holds the command menu (commandMenu) and the pane that shall be shown when a command menu item is selected. This pane is wrapped in a scrollpane (moduleScrollPane).

The example above invokes a method called createAndAddModule() three times. Here is how the method looks like:

private void createAndAddModule(Class<? extends JComponent> panelClass) {
  try {
    String className = panelClass.getSimpleName();
    String title = TKWeek.get(className + ".title");
    final JComponent module = (JComponent) panelClass.newInstance();
    commandMenu.addCommand(new AbstractAction(title) {

      public void actionPerformed(ActionEvent e) {
  } catch (Throwable thr) {
    Logger.getLogger(TKWeekMainFrame.class.getName()).log(Level.SEVERE, null, thr);

To add a command menu item to the CommandMenu, its addCommand() method is called. It is passed an Action, which is used to determine the displayed text. Additionally, its actionPerformed() method is invoked when a command menu item is clicked. As you can see it just sets the viewport view of a scrollpane. Have you noticed that the component need not be referenced anywhere outside this method?

As you can see, there is not much code needed to populate a command menu. What do you think? I am looking forward to hearing from you.

No comments:

Post a Comment