4.1 Button

Perhaps the simplest user interaction to implement is responding to button clicks. The PluggableButtonMorph supports this.

Several of the Morph subclasses are "pluggable". This means they can be configured through composition rather than inheritance. Configuration is achieved by specifying a model object and a selector for messages to be sent to the model object when an interaction occurs.

Instances of the PluggableButtonMorph class can be created with the #model:action:label: class method. The model: keyword specifies a model object, the action: keyword specifies a selector for the model object, and the label: keyword specifies the text that appears in the button.

Let’s demonstrate using a PluggableButtonMorph by defining a class that opens a window containing a single button. Initially the window background color is white. Clicking the button toggles the color between red and blue.

Create the following class.

Object subclass: #ButtonDemo
   instanceVariableNames: 'layout'
   classVariableNames: ''
   poolDictionaries: ''
   category: 'Demo'

Define the following instance methods.

initialize
| button extent window |
button := PluggableButtonMorph
   model: self
      action: #toggleColor
      label: 'Toggle'.
button setBalloonText: 'toggle background color'.
window := SystemWindow new.
window setLabel: 'Button Demo'; addMorph: button.
        
extent := button morphExtent.
"Add some space to the left and right of the button label."
button morphExtent: (extent x + 15) @ extent y.
        
"Set window size to the smallest height that contains its submorphs."
layout := window layoutMorph.
layout padding: 10.
window
   morphExtent: 300 @ layout minimumExtent y;
   openInWorld.
toggleColor
layout color: (
   layout color = Color red
      ifTrue: [ Color blue ]
      ifFalse: [ Color red ] )

Open a Workspace and evaluate ButtonDemo new. Hover over the "Toggle" button for a second to see its tooltip (a.k.a balloon text). Click the "Toggle" button several times and note how the window background color changes.