Adding Menus to the Address Application

Let's add a menubar menu and a popup menu to our address application. Essentially, we'll set the menubar property of AddressMain to a JMenuBar instance. Then we'll add the Address menu to the menubar and give it two items, Add and Remove. The actionPerformed event properties of these items are set to the same handler as for the Add and Remove buttons.

All of this is done from the constructor of AddressMain. It's rather long, so we'll break out the functionality of adding the menu to a method called_init_menu (). Here's the code (from class AddressMain in


# Create the JMenuBar and

# add it to the addressMenu. jmb = JMenuBar()

self.JMenuBar = JMenuBar addressMenu = JMenu("Address")

# Create two menu items. addAddress = JMenuItem("Add") removeAddress = JMenultem("Remove")

# Add the menu items to the menu.

# then add the menu to the menu bar addressMenu.add(addAddress)

addressMenu.add(removeAddress) JMenuBar.add(addressMenu)

# Register the menu items event handler addAddress.actionPerformed = self._addAddress_Clicked removeAddress.actionPerformed= self.__RemoveAddress_Clicke

We also want to add a popup menu to our application that appears when the user clicks the address list. The

_init_popup method is similar to_init_menu, the only difference being that the mousePressed event is handled fon addresses. Notice that, if event .metaDown (in the event handler formousePressed) is true (1), the right mouse button was clicked.

self.popup = NONE #to hold the popup menu self._i nit_popup()

self.addresses.mousePressed = self._popupEvent def _popupEvent(self, event):, event.x, event.y)

self.popup = JPopupMenu("Address") self.addresses.add(self.popup)

# Create two menu items. addAddress = JMenuItem("Add") removeAddress = JMenuItem("Remove")

# Add the menu items to the menu. self.popup.add(addAddress)


# Register the menu item's event handler addAddress.actionPerformed = self. addAddress Clicked removeAddress.actionPerformed= self._RemoveAddress_Cli ck

As an exercise, add and then remove an address entry with the Add and Remove menu items on JMenuBar. Do it again with JPopupMe nu. Also create a duplicate menu item for both the menubar menu and the popup menu that allows an address to be duplicated, that is, copied and pasted into the list.

Was this article helpful?

0 0

Post a comment