Home > Articles > Programming > Java

Java Menus #2: Integrating Menus in JWord

📄 Contents

  1. Swing Solutions: Integrating Menus in JWord
  2. Summary
  3. What's Next?
  • Print
  • + Share This
In this article, you will integrate what you have learned about menus into a Java word processor application: JWord. If you are not already familiar with these components, you may wish to skim over the first article; if you are a seasoned pro and just want to see a new menu event handling architecture then read on!
Like this article? We recommend

Like this article? We recommend

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

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.

 

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020