18.6. Semantic Event Listeners in an Application

The Sketcher program is an obvious candidate for implementing semantic event listeners to support the operation of the menu bar in the SketchFrame class. When you click on an item in one of the pull-down menus, a semantic event will be generated that you can listen for and then use to determine the appropriate program action.

18.6.1. Listening to Menu Items

Let's start with the Elements menu. This is concerned with identifying the type of graphic element to be drawn next, and the color in which it will be drawn. You won't be drawing them for a while, but you can put in the infrastructure to set the type and color for an element without worrying about how it will actually be created and drawn.

To identify the type of element, you can define constants that will act as IDs for the four types of element you have provided for in the menu so far. This will help with the operation of the listeners for the menu item as well as provide a way to identify a particular type of element. Since you'll accumulate quite a number of application-wide constants, it will be convenient to define them as static fields in a class from which they can be imported statically. To be able to import the static fields, the class must be in a named package, so let's set that up. To put the class in a package with the name Constants, you need to set up a directory with this name at a suitable location on your disk, and then use the -classpath option when you compile ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.