Java Menus #2: Integrating Menus in JWord
- Swing Solutions: Integrating Menus in JWord
- Summary
- What's Next?
Integrating Menus into JWord
With the Java Swing menu classes at our disposal, our next goal is to use these in the creation of the JWord menu bar (see Figure 1).
JWord menu screenshot.
Design
So, what features do we want in our menu? Let's take advantage of all of the features that we possibly can:
Keyboard accelerators (hot keys)
Keyboard mnemonics
Image icons
Check box menu items
Radio button menu items
Dynamically adding menu items
MainMenu
The most effective way that I have found for making an application's main menu bar is to separate the menu into its own class (derived from JMenuBar), and to set an instance of it as the JFrame object's menu bar. In this application, we will name the main menu MainMenu and perform all of the creation and initialization in the class's constructor; the initialization will include the configuration of keyboard accelerators and keyboard mnemonics. The class will publicly define all of the JMenuItem objects for easy access by the JFrame that will use it.
With respect to event handling, we will define a method called addActionListener, which will forward the request to all of the menu items in the class.
To demonstrate adding items dynamically to the menu, we will define a method called addOpenedWindow( String strName ), which will add a new window to the Window menu. Besides arranging windows within the application, this menu will enable the user to select the window he wishes to edit; this mechanism will be facilitated through the dynamic creation and addition of JRadioButtonMenuItem objects to the Window menu.
JWord Application
The JWord class will be a JFrame derivative that will host our main menu (and all other GUI classes that we add as we go, such as a toolbar, a status bar, and internal windows.) It will implement the ActionListener interface and add itself as a listener to the MainMenu class.
Now the event handling may look a bit foreign to you (and really, it is just a matter of coding style), but in this example we will use the actionPerformed method in order to delegate the event handling to specific methods in the JWord class. For example, if the File->Open menu item generated the action event, the actionPerformed method will call the JWord class's onFileOpen method. It will all make sense when you look at the code, but the purpose to my madness is to manage explicit actions in their own methods (and to reduce the size of the already monstrous actionPerformed method). That being said, let's move on!
Icons
Some of you might not be as blessed as I am with a keen artistic ability, and you may be in need of some artwork. (Well, if you have seen the icons that I used in my book—Java 2 From Scratch—you may think that I am either delusional or a horrible art critic, but I happen to like two-color nondescriptive icons.)
Sun Microsystems has been generous enough to publicly donate a set of icons with the specific intent of promoting a consistent Java look and feel. (So I guess you are going to have to miss out on my artistic follies!) Take a look at this Web site for the Java Look and Feel Graphics Repository: http://developer.java.sun.com/developer/techDocs/hi/repository/.
The links from this page are particularly useful because they also specify the following information:
Description—Useful information, as well as text that might be placed in an application's status bar.
Name—A short phrase that should appear in menus and on buttons.
ToolTip—A short phrase that should appear as the ToolTip.
Shortcut/accelerator—The keystroke combination (consisting of the given letter and a modifier key) that should activate the method.
Mnemonic—The keystroke that, within the appropriate scope, activates the method.
Filename—The relative path name for the graphics.
Refer back to this page if you ever have a question about what mnemonic or hot key to use.
Because Sun packages these icons in a Java Archive file (JAR), an interesting subtopic in our discussion must include loading icons from a resource. The following listing shows a simple method—getImage()—that loads an image from the Java Look and Feel Graphics Repository.
public ImageIcon getImage( String strFilename ) { // Get an instance of our class Class thisClass = getClass(); // Locate the desired image file and create a URL to it java.net.URL url = thisClass.getResource( "toolbarButtonGraphics/" + strFilename ); // See if we successfully found the image if( url == null ) { System.out.println( "Unable to load the following image: " + strFilename ); return null; } // Get a Toolkit object Toolkit toolkit = Toolkit.getDefaultToolkit(); // Create a new image from the image URL Image image = toolkit.getImage( url ); // Build a new ImageIcon from this and return it to the caller return new ImageIcon( image ); }
The getImage() method starts by getting an instance of the current class, and then asking that class to locate the resource toolbarButtonGraphics/imagefile. For example, if we wanted to load the image for the Cut icon, we would specify toolbarButtonGraphics/general/Cut16.gif.
The image name, including the General folder, is all specific to the JAR file we are using: jlfgr-1_0.jar (Java Look and Feel Graphics Repository). Refer back to http://developer.java.sun.com/developer/techDocs/hi/repository/ and the example at the end of this article for more information.
The getResource() method returns a java.net.URL object pointing to the JAR image file resource; it is always a good idea to verify that the URL is valid before continuing. Next, the getImage() method retrieves the default java.awt.Toolkit object and then asks it to retrieve the image from the java.net.URL object. When it has that image, it constructs an ImageIcon from it and returns that to the caller.
Note that the resource must be included in the current class path: you can either explicitly add the JAR file to the CLASSPATH environment variable or add the JAR file to the Java Runtime Engine’s extensions directory. I recommend adding it to your CLASSPATH environment variable— then you will know absolutely that JAR file is being used. (I have been burned by applications that install a new JRE, and when applications load they suddenly throw exceptions left and right.)
Implementation
At this point, the JWord application is constructed by two classes: MainMenu and JWord.
public JMenu menuFile = new JMenu( "File" ); public JMenuItem fileNew = new JMenuItem( "New", getImage( "general/New16.gif" ) ); public JMenuItem fileOpen = new JMenuItem( "Open", getImage( "general/Open16.gif" ) ); public JMenuItem fileClose = new JMenuItem( "Close" ); ...
First, the MainMenu class defines all of its JMenuItem and JMenu objects as class member variables. Note that these variables are declared with the public access modifier so that the JWord application class can check the source of action events with a simple comparison to mainmenu.fileNew, for example. I do not suspect that the owner of a MainMenu object will be too malicious, and I really do not want to write all of those get methods—the class is large enough already.
You can see that many of the menu items make use of the getImage() method that we talked about in the last section in their constructors.
fileNew.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_N, ActionEvent.CTRL_MASK ) ); fileOpen.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_O, ActionEvent.CTRL_MASK ) ); ...
The constructor begins by setting up accelerators (hot keys) for several of the menu items using the JMenuItem class's setAccelerator() method. For example, File->New has an accelerator of Ctrl+N:
menuFile.setMnemonic( KeyEvent.VK_F ); fileNew.setMnemonic( KeyEvent.VK_N ); fileOpen.setMnemonic( KeyEvent.VK_O ); ...
Next, the constructor sets keyboard mnemonics for every menu item using the JMenuItem class's setMnemonic method; for example, File->New has a mnemonic of N, so pressing Alt+F and then N will generate a file new event:
add( menuFile ); menuFile.add( fileNew ); menuFile.add( fileOpen ); menuFile.add( fileClose ); menuFile.addSeparator(); menuFile.add( fileSave ); ...
Finally, the constructor builds all of the JMenu objects by adding the JMenuItem object to them and subsequently adding them to the JMenuBar class. Remember that the MainMenu class is derived from JMenuBar, so calling the add() method anywhere in the class is permitted.
public void addActionListener( ActionListener listener ) { // Add the ActionListener to our collection of ActionListeners m_vectorActionListeners.addElement( listener ); // Add listener as the action listener for the "File" menu items fileNew.addActionListener( listener ); fileOpen.addActionListener( listener ); fileClose.addActionListener( listener ); fileSave.addActionListener( listener ); ... }
The addActionListener() method forwards the ActionListener object to each of the JMenuItem objects. This way, the menu’s parent must simply call addActionListener once, and it picks up all JMenuItem objects. The MainMenu class maintains a vector list of action listener items so that it always knows who is listening for events (this will be addressed shortly).
We've already discussed the getImage() method: It retrieves the specified image from the Java Look and Feel Graphics Repository and returns the image as an ImageIcon.
Finally, the addOpenedWindow() method adds a JRadioButtonMenuItem to the Window menu and selects it. You may have noticed that we saved the ActionListener objects in addActionListener() into a java.util.Vector object. A vector is nothing more than a dynamic array that can grow and shrink as items are added and removed from it. The decision to use a vector rather than simply saving the single ActionListener (JWord instance) is made for expandability: Various classes can add themselves to the menu as ActionListener objects, and can respond to menu events. (To be completely consistent, we could have added a removeActionListener() method, but we will deal with that later if we need it.) The addOpenedWindow() method iterates through all ofthe registered ActionListener objects and adds each of them as ActionListener objects for the new JRadioButtonMenuItem object.
The addOpenedWindow() method then adds the new menu item to the ButtonGroup: windowOpenedWindows. Recall that the ButtonGroup class manages the radio button (mutually exclusive) state of all buttons added to it. Finally, the addOpenedWindow() method adds the menu item to the Window menu.
Now let's take a look at the JWord class constructor in the following listing:
public JWord() { // Set our title super( "JWord" ); // Set our size setSize( 640, 480 ); // Add our main menu setJMenuBar( m_mainMenu ); // Add ourself as a listener to the menu m_mainMenu.addActionListener( this ); // Center our window Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = getSize(); setBounds( (screenSize.width - windowSize.width) / 2, (screenSize.height - windowSize.height) / 2, windowSize.width, windowSize.height); // Make ourself visible setVisible( true ); // Add a window listener to listen for our window closing addWindowListener ( new WindowAdapter() { public void windowClosing( WindowEvent e ) { // Close our application System.exit( 0 ); } } ); }
The JWord class is derived from JFrame and defines two class member variables: our MainMenu object, and an integer to count the number of windows that have been opened (this is for naming new windows that we create). Its constructor does many of the standard application functions: resizes the JFrame, sets the title, and centers it on the screen. It then sets the MainMenu object as the JMenuBar of the JFrame and finally, adds itself as an action listener to the menu.
public void actionPerformed(ActionEvent e) { // Find out which JMenuItem generated this event // Handle "File->New" if( e.getSource() == m_mainMenu.fileNew ) { onFileNew( e ); } ... }
The actionPerformed() method retrieves the source that generated the action event by calling the ActionEvent class's getSource() method. It compares this source to the various MainMenu JMenuItem objects and forwards the event to a specific event handler. For example, when the File->New menu item is selected, the actionPerformed() method is called with a source of m_mainMenu.fileNew. When this value is discovered, the event is passed on the onFileNew() method. The only unusual ActionEvent handler is for opened windows; remember that opened windows are defined dynamically, so a member variable does not exist inside of the MainMenu class to which we can compare it. You can employ many options to solve this problem, but I took the easiest: Check the class that generated the message, and forward all unknown JRadioButtonMenuItem objects to the onWindowSelect() method.
The code that is used to retrieve the class name of the object that generated the event is in shorthand notation, but could be more easily understood as follows:
JMenuItem menuItem = ( JMenuItem )e.getSource(); Class menuItemClass = menuItem.getClass(); String strClassName = menuItemClass.getName();
if( strClassName.equalsIgnoreCase( “javax.swing.JRadioButtonMenuItem” ) ) { onWindowSelect( e ); }
Almost all of the remaining methods are event handlers that simply print the action to the standard output device (screen):
protected void onFileNew( ActionEvent e ) { System.out.println( "File->New" ); // Add the new menu window to the main menu m_mainMenu.addOpenedWindow( "JWord - Window" + ++m_nWindowCount ); }
The onFileNew() method adds a new window to the Window menu by calling the MainMenu class's addOpenedWindow() method; this is where the window count integer comes in: to name the window.
protected void onWindowSelect( ActionEvent e ) { // Get the JRadioButtonMenuItem that generated this event JRadioButtonMenuItem selectedWindow = ( JRadioButtonMenuItem ) e.getSource(); // Retrieve the name of the window that was selected String strSelectedWindow = selectedWindow.getText(); // Debug output System.out.println( "Window->Selected \"" + strSelectedWindow + "\"" ); }
The onWindowSelect() method demonstrates how to retrieve the name of the menu item that generated the event; we will need this information later in the application.
public static void main( String[] args ) { JWord app = new JWord(); }
Finally, the main() method—the main entry point into a Java application—simply creates an instance of the JWord class.