You will be given all of the code for this step. Although you could go through the step quickly by just adding the code sequentially at the end of the constructor, it is better to proceed slowly. Read through the explanations carefully. You will be adding two more action objects in the next two steps, and adding them to the "File" menu. This step will be used as a model.
There is an AbstractAction class that implements all of the Action interface methods except the actionPerformed() method. Here is the code to create your exit action.
Action exitAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { exit(); } }; exitAction.putValue(Action.NAME, "Exit");In this code, you have defined the actionPerformed() method for the new action to just invoke the exit() method of the FileViewer class. The putValue() message gives a name to the action. When this action is added to a menu, the menu uses the name property as the label on the menu item that it creates.
JMenu fileMenu = new JMenu("File"); fileMenu.add(exitAction);When the file menu receives the add() message, it creates a menu item (class JMenuItem) for the action, using the Action getValue() method to determine the label for the menu item. Then it adds the menu item into the menu.
JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); setJmenuBar(menuBar);The first statement creates the menu bar. The second adds the file menu to the menu bar. The third installs the menu bar into the application top-level window.
Although you have not done so, you can add menu bars and menus to applets using the same code as shown here.
That is all of the code for this step. When you have completed the changes, recompile the FileViewer class and run it again by giving the following command.
java FileViewerYou should see a "File" menu near the top of the application. When you click on it, its "Exit" menu item should pop up. When you click on the "Exit" menu item, the program should terminate.