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:
Here is how to set them up:
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 (
The example above invokes a method called
createAndAddModule() three times. Here is how the method looks like:
To add a command menu item to the
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.