28.12.2012 Views

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Not used<br />

}<br />

public void menuCanceled(MenuEvent evt) {<br />

// Not used<br />

}<br />

});<br />

You can try this code using the command:<br />

j ava <strong>JFC</strong>Book.Chapter6.MenuExample6<br />

The Menu Bar and the Menu System 649<br />

When you click on the File menu, a MenuEvent will be posted from the<br />

JMenu object just before the menu is made visible. When this event is passed<br />

to the listener's menuSelected method, the state of all of its menu items is<br />

adjusted based on the application s internal state. Therefore, the menu items'<br />

state will be correct when the menu is displayed, but may be out-of-date<br />

when it is not. This doesn't matter, of course, because the user can't see that<br />

the menu items are in the wrong state.<br />

As a consequence of implementing the MenuListener, all of the code<br />

that enables and disables menu items that were introduced in the previous<br />

section can be removed. Using a MenuListener is obviously cleaner—the<br />

code is all in one place and it is much more easily understandable. We recommend<br />

using this technique whenever possible.<br />

Using Actions with Menus<br />

So far in this chapter, all of the menu items have been created directly and<br />

ActionListeners have been added to them to handle the event generated<br />

when they are selected. In the last chapter, you saw how useful the concept<br />

of an Action was when handling events from the keyboard, since Actions<br />

make it possible to combine an ActionListener with some state information<br />

needed when the action is to be performed. A useful feature of the<br />

JMenu class is that it allows you to add an Action directly to a menu:<br />

public JMenuItem add(Action action);<br />

In order for this to work properly, you have to create an Action with an<br />

appropriate text string, which is then used as the label of the menu item. For<br />

example, you can use the AbstractAction class to create a suitable<br />

Action. Here's how you might add an Action to process the Save operation:<br />

JMenu menu = new JMenu("File");

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!