Important: The Java API for Cocoa is deprecated in Mac OS X version 10.4 and later. You should use the Objective-C API instead. For a tutorial on using Cocoa with Objective-C, see Cocoa Application Tutorial.
This section guides you through the code-free steps involved in creating a functioning user interface for Currency Converter and explains interesting and important aspects of Cocoa programming along the way.
What Is a Nib File?
Open the Main Nib File
Windows in Cocoa
Resize the Window
Set the Window’s Title and Other Attributes
Set the Application Name in the Menu
Configure a Text Field
Duplicate an Object
Change the Attributes of a Text Field
Assign Labels to the Fields
Configure a Button
Add a Horizontal Decorative Line
Interface Layout and Object Alignment
Finalize the Window Layout
Enable Tabbing Between Text Fields
Set the First Responder for the Currency Converter Window
Test the Interface
Every Cocoa application with a graphical user interface has at least one nib file. The main nib file is loaded automatically when an application launches. It contains the menu bar and generally at least one window along with various other objects. An application can have other nib files as well. Each nib file contains:
Archived objects. Also known in object-oriented terminology as “flattened” or “serialized” objects—meaning that the object has been encoded in such a way that it can be saved to disk (or transmitted over a network connection to another computer) and later restored to memory. Archived objects contain information such as their size, location, and position in the object hierarchy. At the top of the hierarchy of archived objects is the File’s Owner object, a proxy object that points to the actual object that owns the nib file (typically, the one that loaded the nib file from disk).
Images. Image files that you drag and drop on the nib file window or on an object that can accept them (such as a button or image view).
Class references. Interface Builder can store the details of Cocoa objects and objects that you place into static palettes, but it does not know how to archive instances of your custom classes since it doesn’t have access to the code. For these classes, Interface Builder stores a proxy object to which it attaches your custom class information.
Connection information. Information about how objects within the class hierarchies are interconnected. Connector objects special to Interface Builder store this information. When you save a document, its connector objects are archived in the nib file along with the objects they connect.
You use Interface Builder to define an application’s user interface. To open the Currency Converter’s main nib file in Interface Builder:
Locate MainMenu.nib in the Resources subgroup of your project.
Double-click the nib file. This opens the nib file in Interface Builder.
A default menu bar called MainMenu and a window titled “Window” appear when the nib file is opened.
A window in Cocoa looks very similar to windows in other user environments, such as Windows. It is a rectangular area on the screen in which an application displays things such as controls, fields, text, and graphics. Windows can be moved around the screen and stacked on top of each other like pieces of paper. A typical Cocoa window has a title bar, a content area, and several control objects.
Many user-interface objects other than the standard window are windows. Menus, pop-up lists, and pull-down lists are primarily windows, as are all varieties of utility windows and dialogs: attention dialogs, Info windows, drawers, panels, and tool palettes, to name a few. In fact, anything drawn on the screen must appear in a window. End users, however, may not recognize or refer to them as “windows.”
Two interacting systems create and manage Cocoa windows. A window is created by the Window Server. The Window Server is a process that uses the internal window management portion of Quartz (the low-level drawing system) to draw, resize, hide, and move windows using Quartz graphics routines. The Window Server also detects user events (such as mouse clicks) and forwards them to applications.
The window that the Window Server creates is paired with an object supplied by the Application Kit framework (AppKit). The object supplied is an instance of the NSWindow class. Each physical window in a Cocoa program is managed by an instance of NSWindow or a subclass of it. For information on AppKit, see The Cocoa Frameworks in Cocoa Fundamentals Guide.
When you create an NSWindow object, the Window Server creates the physical window that the NSWindow object manages. The NSWindow class offers a number of instance methods through which you customize the operation of its onscreen window.
In a running Cocoa application, NSWindow objects occupy a middle position between an instance of NSApplication and the views of the application. (A view is an object that can draw itself and detect user events.) The NSApplication object keeps a list of its windows and tracks the current status of each. Each NSWindow object manages a hierarchy of views in addition to its window.
At the top of this hierarchy is the content view, which fits just within the window’s content rectangle. The content view encloses all other views (its subviews) that come below it in the hierarchy. The NSWindow distributes events to views in the hierarchy and regulates coordinate transformations among them.
Another rectangle, the frame rectangle, defines the outer boundary of the window and includes the title bar and the window’s controls. Cocoa uses the bottom-left corner of the frame rectangle as the origin for the base coordinate system, unlike Carbon and Classic applications, which use the top-left corner. Views draw themselves in coordinate systems transformed from (and relative to) this base coordinate system.
Windows have numerous characteristics. They can be onscreen or offscreen. Onscreen windows are “layered” on the screen in tiers managed by the Window Server. Onscreen windows can also have a status: key or main.
Key windows respond to key presses for an application and are the primary recipient of messages from menus and panels. Usually, a window is made key when the user clicks it. Each application can have only one key window.
An application has one main window, which can often have key status as well. The main window is the principal focus of user actions for an application. Often user actions in a modal key window (typically a panel such as the Font window or an Info window) have a direct effect on the main window.
Make the window smaller by dragging the bottom-right corner of the window inward, as shown in Figure 1-5.
You can resize the window more precisely in the Size pane in the NSWindow inspector.
Choose Show Inspector from the Tools menu.
Choose Size from the inspector pop-up menu.
In the Content Rectangle group, choose Width/Height from the second pop-up menu.
Type 400 in the width (“w”) field and 200 in the height (“h”) field, as shown in Figure 1-6.
Set other attributes for the window in the NSWindow inspector:
Choose Attributes from the inspector pop-up menu and change the window’s title to “Currency Converter”. Press Return to lock in the change.
Verify that the “Visible at launch time” option is selected.
Deselect the Zoom option in the “Title bar controls” group.
Interface Builder places the term “NewApplication” in place of the application name in the menu bar. You must change this text to the application name in all menu items that include the application name, such as the application menu and the Help menu.
In the MainMenu window, double-click NewApplication, and press the Space bar.
In the NSMenuItem inspector, enter Currency Converter in the Title text field and press Return.
In the MainMenu window, click Currency Converter, double-click Quit NewApplication, and type Quit Currency Converter.

Click Help and replace “New Application Help” with “Currency Converter Help”.
The Interface Builder palette window contains several user-interface elements or controls that you can drag into a window or menu to create an application’s user interface. You open the Interface Builder palette window—shown in Figure 1-7—by choosing Tools > Palettes > Show Palettes.
Click the text toolbar item in the palette window (shown as the third toolbar item in Figure 1-7) and drag a text field object to the top-right corner of the Currency Converter window. Notice that Interface Builder helps you place objects according to the Apple human interface guidelines by displaying layout guides when an object is dragged close to the proper distance from neighboring objects or the edge of the window.
Increase the text field’s size so that it’s about 50% wider. Resize the text field by grabbing a handle and dragging in the direction you want it to grow. In this case, drag the left handle to the left to enlarge the text field, as shown in Figure 1-8.
Currency Converter needs two more text fields, both the same size as the first. There are two options: You can drag another text field from the palette to the window and make it the same size as the first one; or you can duplicate the text field already in the window.
To duplicate the text field in the Currency Converter window:
Select the text field, if it is not already selected.
Choose Duplicate (Command-D) from the Edit menu. The new text field appears slightly offset from the original field.
Position the new text field under the first text field. Notice that the layout guides appear and Interface Builder snaps the text field into place.
To make the third text field, press Command-D. Notice that Interface Builder remembered the offset from the previous Duplicate command and automatically applied it to the newly created text field.
As a shortcut, you can also Option-drag the original text field to duplicate it.
The bottom text field displays the results of the currency-conversion computation and should therefore have different attributes than the other text fields: It must not be editable by the user.
Select the third text field.
In the NSTextField inspector, choose Attributes from the pop-up menu.
Deselect the Editable option so that users are not allowed to alter the contents of the text field. Make sure the Selectable option is selected so that users can copy and paste the contents of the text field to other applications.
Text fields without labels would be confusing, so add labels by using the ready-made label object from the Text palette.
Drag a System Font Text element onto the window from the Cocoa Text palette.

In the NSTextField inspector, enter Exchange Rate per $1: in the Title text field.
Make the text label right aligned. With the System Font Text element selected, click the third button from the left in the Alignment area in the inspector, as shown in Figure 1-9.
Duplicate the text label twice. Set the title of the second text label to “Dollars to Convert:” and the title for the third text label to “Amount in Other Currency:”.
Align the new text labels as shown in Figure 1-10. You may need to expand the text labels so that their entire titles are visible.
The currency conversion should be invoked either by clicking a button or pressing Return.
Drag the Button element from the Cocoa Controls palette to the bottom-right corner of the window.
Double-click the button and change its title to “Convert”.
Choose Attributes from the NSButton inspector pop-up menu and then choose Return from the Key Equiv pop-up menu. This makes the button respond to the Return key as well as clicks.
Align the button under the text fields:
Drag the button downward until the layout guide appears and then release it.
With the button still selected, hold down the Option key. If you move the pointer around, Interface Builder shows you the distance from the button to the object over which the pointer is hovering.
With the Option key still down and the pointer over the Amount in Other Currency text field, use the arrow keys to nudge the button so that its center is aligned with the center of the text field, as shown in Figure 1-11.
You probably noticed that the final interface for Currency Converter has a decorative line between the text fields and the button. To add the line to the Currency Converter window:
Drag a horizontal line element from the Cocoa Controls palette to the Currency Converter window.
Drag the endpoints of the line until the line extends across the window, as shown in Figure 1-12.
Move the Convert button up until the layout guide appears below the Amount in Other Currency text field, and shorten the window until the horizontal layout guide appears below the Convert button.
In order to make an attractive user interface, you must be able to visually align interface objects in rows and columns. “Eyeballing” the alignments can be very difficult; and typing in x/y coordinates by hand is tedious and time consuming. Aligning Aqua interface elements is made even more difficult because the elements have shadows and user interface guideline metrics do not typically take the shadows into account. Interface Builder uses visual guides and layout rectangles to help you with object alignment.
In Cocoa, all drawing is done within the bounds of an object’s frame. Because interface objects have shadows, they do not visually align correctly if you align the edges of the frames. For example, the Apple user interface guidelines say that a push button should be 20 pixels tall, but you actually need a frame of 32 pixels for both the button and its shadow. The layout rectangle is what you must align. You can view the layout rectangles of objects in Interface Builder using the Show Layout Rectangles command (Command-L) in the Layout menu.
Interface Builder gives you several ways to align objects in a window:
Dragging objects with the mouse in conjunction with the layout guides
Pressing arrow keys (with the grid off, the selected objects move one pixel)
Using a reference object to put selected objects in rows and columns
Using the built-in alignment functions
Specifying origin points in the Size pane in the inspector
The Alignment and Guides submenus in the Layout menu provide various alignment commands and tools, including the Alignment window, which contains controls you can use to perform common alignment operations.
Currency Converter’s interface is almost complete. The finishing touch is to resize the window so that all the user-interface elements are centered and properly aligned to each edge. Currently, the objects are aligned only to the top and right edges.
Perform these steps to finalize the Currency Converter window:
Select the Amount in Other Currency text label and extend the selection (Shift-click) to include the other two.
Resize all the labels to their minimum width by choosing Size to Fit in the Layout menu.
Choose Same Size from the Layout menu to make the selected text labels the same size.
Choose Layout > Alignment > Align Left Edges.
Drag the labels towards the left edge of the window, and release them when the layout guide appears.
Select the three text fields and drag them to the left, again using the guides to help you find the proper position.
Shorten the horizontal separator and move the button into position again under the text fields.
Make the window shorter and narrower until the layout guides appear to the right of the text fields and below the Convert button.
At this point the application’s window should look like Figure 1-13.
The final step in composing the Currency Converter user interface has more to do with behavior than with appearance. You want the user to be able to tab from the first editable field to the second, and back to the first. Many objects in Interface Builder’s palettes have an outlet named nextKeyView. This variable identifies the next object to receive keyboard events when the user presses the Tab key (or the previous object when Shift-Tab is pressed). A Cocoa application by default makes its “best guess” about how to handle text field tabbing, but this guess often produces unexpected results. If you want correct interfield tabbing, you must connect fields through the nextKeyView outlet:
Select the Exchange Rate text field.
Control-drag a connection from the Exchange Rate text field to the Dollars to Convert text field, as shown in Figure 1-14.
In the inspector for the Dollars to Convert text field click Outlets, select nextKeyView, and click Connect. The nextKeyView outlet identifies the next object to respond to events after the Tab key is pressed.
Repeat the same procedure, going from the Dollars to Convert text field to the Exchange Rate text field.
In “Enable Tabbing Between Text Fields,” you set up the key view loop using Interface Builder, establishing connections between the nextKeyView outlets of the two text fields. Now you must set the window’s initialFirstResponder outlet to the text field that you want selected when the window is first displayed onscreen. If you do not set this outlet, the window sets a key loop and picks a default initial first responder for you (not necessarily the same as the one you would have specified).
To set the initialFirstResponder outlet for the Currency Converter window:
Control-drag a connection from the Window instance in the MainMenu.nib window to the Exchange Rate text field, as shown in Figure 1-15.
In the inspector for the Exchange Rate text field, select initialFirstResponder and click Connect.
The Currency Converter user interface is now complete.
Interface Builder lets you test an application’s user interface without having to write code. To test the Currency Converter user interface:
Choose File > Save to save your work.
Choose File > Test Interface.
Try various user operations, such as tabbing, and cutting and pasting between text fields.
When finished, choose Quit Currency Converter from the Interface Builder application menu to exit test mode.
Notice that the screen position of the Currency Converter window in Interface Builder is used as the initial position for the window when the application is launched. Place the window near the top left corner of the screen so that it’s in a convenient (and traditional) initial location.
Last updated: 2006-10-03