Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Roll Your Own Swing-based XML Editor (Part III)-2 : Page 2


advertisement

Build the Menu Components
A JMenu component consists of several objects: a menu bar, one or more menus, and one or menu items. The menu bar contains menus, which in turn contain the menu items. The Swing component names for each of these are quite intuitive (JMenuBar, JMenu, and JMenuItem, respectively).

Below is the entire code required to create a minimal "File" menu containing a single menu item:

JMenu fileMenu = new JMenu( "File" );
	JmenuItem exitItem = new JMenuItem( "Exit" );
	fileMenu.add( exitItem );
	
	JmenuBar menuBar = new JMenuBar();
	menuBar.add( fileMenu );
	setJMenuBar( menuBar );


This process should seem very familiar. A JMenu component is built, as any other Java GUI component is built. The innermost elements are added to their immediate parents, until all elements have defined an appropriate container.

Returning to the XmlEditor case study, we have actually created a more complete file menu with the ability to create a new XML document, open an existing document, save a document, and exit. We'll learn more about that in the next section.

Handle the Menu Events
Let's say that we want to create a typical file menu, allowing our users to create a new document, open an existing document, save the current document, and exit the application. Now that we know how to build the menu itself, how do we go about responding to the user's menu selection? As with other Swing components, the answer lies within the event model and listener components that are made available.

The most basic way to handle a menu selection is the add an action listener to a menu item: exitItem.addActionListener( new exitMenuHandler() ); When dealing with complex event handling(as menu systems tend to become complex), it is considered good practice to define event handlers as separate classes. The example given above is adding an action listener of type exitMenuHandler. This type will be defined later in the application. Below is a minimal definition for an exitMenuHandler class:

class exitMenuHandler implements ActionListener {
 public void actionPerformed( ActionEvent ae ) {
	System.exit(0);
 }
} 

While this implemention might seem too simplistic to warrant a separate class definition, when we define the event handling code for opening and saving documents, you will recognize the value in separating this functionality into a separate class file. Additionally, this approach would allow you to reuse common menu functionality between different applications.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date