On this page:
1.1.1 Core Windowing Classes
1.1.2 Geometry Management Containees Containers Defining New Types of Containers
1.1.3 Mouse and Keyboard Events
1.1.4 Event Dispatching and Eventspaces Event Types and Priorities Eventspaces and Threads Creating and Setting the Eventspace Exceptions and Continuation Jumps

1.1 Windowing

The Racket windowing toolbox provides the basic building blocks of GUI programs, including frames (top-level windows), modal dialogs, menus, buttons, check boxes, text fields, and radio buttons. The toolbox provides these building blocks via built-in classes, such as the frame% class:

  ; Make a frame by instantiating the frame% class
  (define frame (new frame% [label "Example"]))
  ; Show the frame by calling its show method
  (send frame show #t)

The built-in classes provide various mechanisms for handling GUI events. For example, when instantiating the button% class, the programmer supplies an event callback procedure to be invoked when the user clicks the button. The following example program creates a frame with a text message and a button; when the user clicks the button, the message changes:

  ; Make a frame by instantiating the frame% class
  (define frame (new frame% [label "Example"]))
  ; Make a static text message in the frame
  (define msg (new message% [parent frame]
                            [label "No events so far..."]))
  ; Make a button in the frame
  (new button% [parent frame]
               [label "Click Me"]
               ; Callback procedure for a button click:
               (callback (lambda (button event)
                           (send msg set-label "Button click"))))
  ; Show the frame by calling its show method
  (send frame show #t)

Programmers never implement the GUI event loop directly. Instead, the system automatically pulls each event from an internal queue and dispatches the event to an appropriate window. The dispatch invokes the window’s callback procedure or calls one of the window’s methods. In the above program, the system automatically invokes the button’s callback procedure whenever the user clicks Click Me.

If a window receives multiple kinds of events, the events are dispatched to methods of the window’s class instead of to a callback procedure. For example, a drawing canvas receives update events, mouse events, keyboard events, and sizing events; to handle them, a programmer must derive a new class from the built-in canvas% class and override the event-handling methods. The following expression extends the frame created above with a canvas that handles mouse and keyboard events:

  ; Derive a new canvas (a drawing window) class to handle events
  (define my-canvas%
    (class canvas% ; The base class is canvas%
      ; Define overriding method to handle mouse events
      (define/override (on-event event)
        (send msg set-label "Canvas mouse"))
      ; Define overriding method to handle keyboard events
      (define/override (on-char event)
        (send msg set-label "Canvas keyboard"))
      ; Call the superclass init, passing on all init args
  ; Make a canvas that handles events in the frame
  (new my-canvas% [parent frame])

After running the above code, manually resize the frame to see the new canvas. Moving the cursor over the canvas calls the canvas’s on-event method with an object representing a motion event. Clicking on the canvas calls on-event. While the canvas has the keyboard focus, typing on the keyboard invokes the canvas’s on-char method.

The system dispatches GUI events sequentially; that is, after invoking an event-handling callback or method, the system waits until the handler returns before dispatching the next event. To illustrate the sequential nature of events, we extend the frame again, adding a Pause button:

  (new button% [parent frame]
               [label "Pause"]
               [callback (lambda (button event) (sleep 5))])

After the user clicks Pause, the entire frame becomes unresponsive for five seconds; the system cannot dispatch more events until the call to sleep returns. For more information about event dispatching, see Event Dispatching and Eventspaces.

In addition to dispatching events, the GUI classes also handle the graphical layout of windows. Our example frame demonstrates a simple layout; the frame’s elements are lined up top-to-bottom. In general, a programmer specifies the layout of a window by assigning each GUI element to a parent container. A vertical container, such as a frame, arranges its children in a column, and a horizontal container arranges its children in a row. A container can be a child of another container; for example, to place two buttons side-by-side in our frame, we create a horizontal panel for the new buttons:

  (define panel (new horizontal-panel% [parent frame]))
  (new button% [parent panel]
               [label "Left"]
               [callback (lambda (button event)
                           (send msg set-label "Left click"))])
  (new button% [parent panel]
               [label "Right"]
               [callback (lambda (button event)
                           (send msg set-label "Right click"))])

For more information about window layout and containers, see Geometry Management.

1.1.1 Core Windowing Classes

The fundamental graphical element in the windowing toolbox is an area. The following classes implement the different types of areas in the windowing toolbox:

As suggested by the above listing, certain areas, called containers, manage certain other areas, called containees. Some areas, such as panels, are both containers and containees.

Most areas are windows, but some are non-windows. A window, such as a panel, has a graphical representation, receives keyboard and mouse events, and can be disabled or hidden. In contrast, a non-window, such as a pane, is useful only for geometry management; a non-window does not receive mouse events, and it cannot be disabled or hidden.

Every area is an instance of the area<%> interface. Each container is also an instance of the area-container<%> interface, whereas each containee is an instance of subarea<%>. Windows are instances of window<%>. The area-container<%>, subarea<%>, and window<%> interfaces are subinterfaces of area<%>.

The following diagram shows more of the type hierarchy under area<%>:



       |                  |                 |

  subarea<%>          window<%>      area-container<%>      

       |____       _______|__________       |

            |      |                |       |

           subwindow<%>          area-container-window<%>

        ________|________                |

        |               |                |

     control<%>       canvas<%>   top-level-window<%>

The diagram below extends the one above to show the complete type hierarchy under area<%>. (Some of the types are represented by interfaces, and some types are represented by classes. In principle, every area type should be represented by an interface, but whenever the windowing toolbox provides a concrete implementation, the corresponding interface is omitted from the toolbox.) To avoid intersecting lines, the hierarchy is drawn for a cylindrical surface; lines from subarea<%> and subwindow<%> wrap from the left edge of the diagram to the right edge.



        |               |                   |

      subarea<%>     window<%>       area-container<%>      

<<<____|____       _____|__________       __|___  ___________________<<<

            |      |              |       |    |  |                  

           subwindow<%>           |       |    |  |                  

<<<______________|___________     |       |    |  |                 _<<<

            |               |     |       |    pane%                |

       control<%>           |     |       |     |- horizontal-pane% |

        |- message%         |     |       |     |- vertical-pane%   |

        |- button%          |     |       |                         |

        |- check-box%       |  area-container-window<%>             |

        |- slider%          |        |                              |

        |- gauge%           |        |            __________________|

        |- text-field%      |        |            |   

            |- combo-field% |        |-------- panel%       

        |- radio-box%       |        |          |- horizontal-panel%

        |- list-control<%>  |        |          |- vertical-panel%

            |- choice%      |        |              |- tab-panel%

            |- list-box%    |        |              |- group-box-panel%

                            |        |

                            |        |- top-level-window<%>

                            |            |- frame% 

                         canvas<%>       |- dialog%

                          |- canvas%

                          |- editor-canvas%

Menu bars, menus, and menu items are graphical elements, but not areas (i.e., they do not have all of the properties that are common to areas, such as an adjustable graphical size). Instead, the menu classes form a separate container–containee hierarchy:

The following diagram shows the complete type hierarchy for the menu system:

    menu-item<%>                menu-item-container<%> 

        |                              | 

        |- separator-menu-item%   _____|___ 

        |- labelled-menu-item<%>  |       |- menu-bar% 

            _________|_________   |       |- popup-menu% 

            |                 |   | 

            |                 menu%


            |- selectable-menu-item<%>               

                |- menu-item%                        

                |- checkable-menu-item%

1.1.2 Geometry Management

The windowing toolbox’s geometry management makes it easy to design windows that look right on all platforms, despite different graphical representations of GUI elements. Geometry management is based on containers; each container arranges its children based on simple constraints, such as the current size of a frame and the natural size of a button.

The built-in container classes include horizontal panels (and panes), which align their children in a row, and vertical panels (and panes), which align their children in a column. By nesting horizontal and vertical containers, a programmer can achieve most any layout. For example, we can construct a dialog with the following shape:


  |              -------------------------------------   |

  |  Your name: |                                     |  |

  |              -------------------------------------   |

  |                    --------     ----                 |

  |                   ( Cancel )   ( OK )                |

  |                    --------     ----                 |


with the following program:

  ; Create a dialog
  (define dialog (instantiate dialog% ("Example")))
  ; Add a text field to the dialog
  (new text-field% [parent dialog] [label "Your name"])
  ; Add a horizontal panel to the dialog, with centering for buttons
  (define panel (new horizontal-panel% [parent dialog]
                                       [alignment '(center center)]))
  ; Add Cancel and Ok buttons to the horizontal panel
  (new button% [parent panel] [label "Cancel"])
  (new button% [parent panel] [label "Ok"])
  (when (system-position-ok-before-cancel?)
    (send panel change-children reverse))
  ; Show the dialog
  (send dialog show #t)

Each container arranges its children using the natural size of each child, which usually depends on instantiation parameters of the child, such as the label on a button or the number of choices in a radio box. In the above example, the dialog stretches horizontally to match the minimum width of the text field, and it stretches vertically to match the total height of the field and the buttons. The dialog then stretches the horizontal panel to fill the bottom half of the dialog. Finally, the horizontal panel uses the sum of the buttons’ minimum widths to center them horizontally.

As the example demonstrates, a stretchable container grows to fill its environment, and it distributes extra space among its stretchable children. By default, panels are stretchable in both directions, whereas buttons are not stretchable in either direction. The programmer can change whether an individual GUI element is stretchable.

The following subsections describe the container system in detail, first discussing the attributes of a containee in Containees, and then describing the attributes of a container in Containers. In addition to the built-in vertical and horizontal containers, programmers can define new types of containers as discussed in the final subsection, Defining New Types of Containers. Containees

Each containee, or child, has the following properties:

A container arranges its children based on these four properties of each containee. A containee’s parent container is specified when the containee is created, and the parent cannot be changed. However, a containee can be hidden or deleted within its parent, as described in Containers.

The graphical minimum size of a particular containee, as reported by get-graphical-min-size, depends on the platform, the label of the containee (for a control), and style attributes specified when creating the containee. For example, a button’s minimum graphical size ensures that the entire text of the label is visible. The graphical minimum size of a control (such as a button) cannot be changed; it is fixed at creation time. (A control’s minimum size is not recalculated when its label is changed.) The graphical minimum size of a panel or pane depends on the total minimum size of its children and the way that they are arranged.

To select a size for a containee, its parent container considers the containee’s requested minimum size rather than its graphical minimum size (assuming the requested minimum is larger than the graphical minimum). Unlike the graphical minimum, the requested minimum size of a containee can be changed by a programmer at any time using the min-width and min-height methods.

Unless a containee is stretchable (in a particular direction), it always shrinks to its minimum size (in the corresponding direction). Otherwise, containees are stretched to fill all available space in a container. Each containee begins with a default stretchability. For example, buttons are not initially stretchable, whereas a one-line text field is initially stretchable in the horizontal direction. A programmer can change the stretchability of a containee at any time using the stretchable-width and stretchable-height methods.

A margin is space surrounding a containee. Each containee’s margin is independent of its minimum size, but from the container’s point of view, a margin effectively increases the minimum size of the containee. For example, if a button has a vertical margin of 2, then the container must allocate enough room to leave two pixels of space above and below the button, in addition to the space that is allocated for the button’s minimum height. A programmer can adjust a containee’s margin with horiz-margin and vert-margin. The default margin is 2 for a control, and 0 for any other type of containee.

In practice, the requested minimum size and margin of a control are rarely changed, although they are often changed for a canvas. Stretchability is commonly adjusted for any type of containee, depending on the visual effect desired by the programmer. Containers

A container has the following properties:

These properties are factored into the container’s calculation of its own size and the arrangement of its children. For a container that is also a containee (e.g., a panel), the container’s requested minimum size and stretchability are the same as for its containee aspect.

A containee’s parent container is specified when the containee is created, and the parent cannot be changed. However, a containee window can be hidden or deleted within its parent container (but a non-window containee cannot be hidden or deleted):

When a child is created, it is initially shown and non-deleted. A deleted child is subject to garbage collection when no external reference to the child exists. A list of non-deleted children (hidden or not) is available from a container through its get-children method.

The order of the children in a container’s non-deleted list is significant. For example, a vertical panel puts the first child in its list at the top of the panel, and so on. When a new child is created, it is put at the end of its container’s list of children. The order of a container’s list can be changed dynamically via the change-children method. (The change-children method can also be used to activate or deactivate children.)

The graphical minimum size of a container, as reported by get-graphical-min-size, is calculated by combining the minimum sizes of its children (summing them or taking the maximum, as appropriate to the layout strategy of the container) along with the spacing and border margins of the container. A larger minimum may be specified by the programmer using min-width and min-height methods; when the computed minimum for a container is larger than the programmer-specified minimum, then the programmer-specified minimum is ignored.

A container’s spacing determines the amount of space left between adjacent children in the container, in addition to any space required by the children’s margins. A container’s border margin determines the amount of space to add around the collection of children; it effectively decreases the area within the container where children can be placed. A programmer can adjust a container’s border and spacing dynamically via the border and spacing methods. The default border and spacing are 0 for all container types.

Because a panel or pane is a containee as well as a container, it has a containee margin in addition to its border margin. For a panel, these margins are not redundant because the panel can have a graphical border; the border is drawn inside the panel’s containee margin, but outside the panel’s border margin.

For a top-level-window container, such as a frame or dialog, the container’s stretchability determines whether the user can resize the window to something larger than its minimum size. Thus, the user cannot resize a frame that is not stretchable. For other types of containers (i.e., panels and panes), the container’s stretchability is its stretchability as a containee in some other container. All types of containers are initially stretchable in both directions – except instances of grow-box-spacer-pane%, which is intended as a lightweight spacer class rather than a useful container class – but a programmer can change the stretchability of an area at any time via the stretchable-width and stretchable-height methods.

The alignment specification for a container determines how it positions its children when the container has leftover space. (A container can only have leftover space in a particular direction when none of its children are stretchable in that direction.) For example, when the container’s horizontal alignment is 'left, the children are left-aligned in the container and leftover space is accumulated to the right. When the container’s horizontal alignment is 'center, each child is horizontally centered in the container. A container’s alignment is changed with the set-alignment method. Defining New Types of Containers

Although nested horizontal and vertical containers can express most layout patterns, a programmer can define a new type of container with an explicit layout procedure. A programmer defines a new type of container by deriving a class from panel% or pane% and overriding the container-size and place-children methods. The container-size method takes a list of size specifications for each child and returns two values: the minimum width and height of the container. The place-children method takes the container’s size and a list of size specifications for each child, and returns a list of sizes and placements (in parallel to the original list).

An input size specification is a list of four values:

For place-children, an output position and size specification is a list of four values:

The widths and heights for both the input and output include the children’s margins. The returned position for each child is automatically incremented to account for the child’s margin in placing the control.

1.1.3 Mouse and Keyboard Events

Whenever the user moves the mouse, clicks or releases a mouse button, or presses a key on the keyboard, an event is generated for some window. The window that receives the event depends on the current state of the graphic display:

Controls, such as buttons and list boxes, handle keyboard and mouse events automatically, eventually invoking the callback procedure that was provided when the control was created. A canvas propagates mouse and keyboard events to its on-event and on-char methods, respectively.

A mouse and keyboard event is delivered in a special way to its window. Each ancestor of the receiving window gets a chance to intercept the event through the on-subwindow-event and on-subwindow-char methods. See the method descriptions for more information.

The default on-subwindow-char method for a top-level window intercepts keyboard events to detect menu-shortcut events and focus-navigation events. See on-subwindow-char in frame% and on-subwindow-char in dialog% for details. Certain OS-specific key combinations are captured at a low level, and cannot be overridden. For example, under Windows and X, pressing and releasing Alt always moves the keyboard focus to the menu bar. Similarly, Alt-Tab switches to a different application under Windows. (Alt-Space invokes the system menu under Windows, but this shortcut is implemented by on-system-menu-char, which is called by on-subwindow-char in frame% and on-subwindow-char in dialog%.)

1.1.4 Event Dispatching and Eventspaces

A graphical user interface is an inherently multi-threaded system: one thread is the program managing windows on the screen, and the other thread is the user moving the mouse and typing at the keyboard. GUI programs typically use an event queue to translate this multi-threaded system into a sequential one, at least from the programmer’s point of view. Each user action is handled one at a time, ignoring further user actions until the previous one is completely handled. The conversion from a multi-threaded process to a single-threaded one greatly simplifies the implementation of GUI programs.

Despite the programming convenience provided by a purely sequential event queue, certain situations require a less rigid dialog with the user:

An eventspace is a context for processing GUI events. Each eventspace maintains its own queue of events, and events in a single eventspace are dispatched sequentially by a designated handler thread. An event-handling procedure running in this handler thread can yield to the system by calling yield, in which case other event-handling procedures may be called in a nested (but single-threaded) manner within the same handler thread. Events from different eventspaces are dispatched asynchronously by separate handler threads.

When a frame or dialog is created without a parent, it is associated with the current eventspace as described in Creating and Setting the Eventspace. Events for a top-level window and its descendants are always dispatched in the window’s eventspace. Every dialog is modal; a dialog’s show method implicitly calls yield to handle events while the dialog is shown. (See also Eventspaces and Threads for information about threads and modal dialogs.) Furthermore, when a modal dialog is shown, the system disables all other top-level windows in the dialog’s eventspace, but windows in other eventspaces are unaffected by the modal dialog. (Disabling a window prevents mouse and keyboard events from reaching the window, but other kinds of events, such as update events, are still delivered.) Event Types and Priorities

In addition to events corresponding to user and windowing actions, such as button clicks, key presses, and updates, the system dispatches two kinds of internal events: timer events and explicitly queued events.

Timer events are created by instances of timer%. When a timer is started and then expires, the timer queues an event to call the timer’s notify method. Like a top-level window, each timer is associated with a particular eventspace (the current eventspace as described in Creating and Setting the Eventspace) when it is created, and the timer queues the event in its eventspace.

Explicitly queued events are created with queue-callback, which accepts a callback procedure to handle the event. The event is enqueued in the current eventspace at the time of the call to queue-callback, with either a high or low priority as specified by the (optional) second argument to queue-callback.

An eventspace’s event queue is actually a priority queue with events sorted according to their kind, from highest-priority (dispatched first) to lowest-priority (dispatched last):

Although a programmer has no direct control over the order in which events are dispatched, a programmer can control the timing of dispatches by setting the event dispatch handler via the event-dispatch-handler parameter. This parameter and other eventspace procedures are described in more detail in Eventspaces. Eventspaces and Threads

When a new eventspace is created, a corresponding handler thread is created for the eventspace. When the system dispatches an event for an eventspace, it always does so in the eventspace’s handler thread. A handler procedure can create new threads that run indefinitely, but as long as the handler thread is running a handler procedure, no new events can be dispatched for the corresponding eventspace.

When a handler thread shows a dialog, the dialog’s show method implicitly calls yield for as long as the dialog is shown. When a non-handler thread shows a dialog, the non-handler thread simply blocks until the dialog is dismissed. Calling yield with no arguments from a non-handler thread has no effect. Calling yield with a semaphore from a non-handler thread is equivalent to calling semaphore-wait. Creating and Setting the Eventspace

Whenever a frame, dialog, or timer is created, it is associated with the current eventspace as determined by the current-eventspace parameter (see Parameters).

The make-eventspace procedure creates a new eventspace. The following example creates a new eventspace and a new frame in the eventspace (the parameterize syntactic form temporary sets a parameter value):

  (let ([new-es (make-eventspace)])
    (parameterize ([current-eventspace new-es])
      (new frame% [label "Example"])))

When an eventspace is created, it is placed under the management of the current custodian. When a custodian shuts down an eventspace, all frames and dialogs associated with the eventspace are destroyed (without calling can-close? or on-close in top-level-window<%>), all timers in the eventspace are stopped, and all enqueued callbacks are removed. Attempting to create a new window, timer, or explicitly queued event in a shut-down eventspace raises the exn:misc exception.

An eventspace is a synchronizable event (not to be confused with a GUI event), so it can be used with sync. As a synchronizable event, an eventspace is in a blocking state when a frame is visible, a timer is active, a callback is queued, or a menu-bar% is created with a 'root parent. (Note that the blocking state of an eventspace is unrelated to whether an event is ready for dispatching.) Exceptions and Continuation Jumps

Whenever the system dispatches an event, the call to the handler procedure is wrapped so that full continuation jumps are not allowed to escape from the dispatch, and escape continuation jumps are blocked at the dispatch site. The following block procedure illustrates how the system blocks escape continuation jumps:

  (define (block f)
    ; calls f and returns void if f tries to escape
    (let ([done? #f])
      (let/ec k
          (lambda () (begin0 (f) (set! done? #t)))
          (lambda () (unless done? (k (void))))))))


  > (block (lambda () 5))


  > (let/ec k (block (lambda () (k 10))))
  > (let/ec k ((lambda () (k 10))) 11)


  > (let/ec k (block (lambda () (k 10))) 11)


Calls to the event dispatch handler are also protected with block.

This blocking of continuation jumps complicates the interaction between with-handlers and yield (or the default event dispatch handler). For example, in evaluating the expression

  (with-handlers ([(lambda (x) #t)
                   (lambda (x) (error "error during yield"))])

the "error during yield" handler is never called, even if a callback procedure invoked by yield raises an exception. The with-handlers expression installs an exception handler that tries to jump back to the context of the with-handlers expression before invoking a handler procedure; this jump is blocked by the dispatch within yield, so "error during yield" is never printed. Exceptions during yield are “handled” in the sense that control jumps out of the event handler, but yield may dispatch another event rather than escaping or returning.

The following expression demonstrates a more useful way to handle exceptions within yield, for the rare cases where such handling is useful:

  (let/ec k
     (lambda (x)
       (error "error during yield")
     (lambda ()

This expression installs an exception handler that prints an error message before trying to escape. Like the continuation escape associated with with-handlers, the escape to k never succeeds. Nevertheless, if an exception is raised by an event handler during the call to yield, an error message is printed before control returns to the event dispatcher within yield.