Behaviors

Overview

A user interface has to do something when a person uses it. When a button is pressed, a message appears. When a timer starts, it counts down. In Quorum, the code that runs when something happens goes in a behavior. A behavior is a class that inherits from Behavior. In this tutorial, you will write a behavior that runs once when a button on a page is pressed, and a behavior that runs a little at a time, over several seconds.

Goals

You have the following goals for this lesson:

By the end of this lesson, you can

  • Learn the four main actions of the Behavior class and when each one runs
  • Write a behavior and attach it to a button on a page with SetBehavior
  • Write a behavior that runs over time and attach it with AddBehavior
  • Show changes in a way that every person can find, including screen reader users

Warm up

Think about a microwave. You press "Start", and it runs for a set time, then beeps and stops. What happens once at the start? What happens over and over while it runs? What happens once at the end? Consider one other device that works the same way.

Vocabulary

You will be learning about the following vocabulary words:

Vocabulary
TermDefinition
BehaviorA class with code that runs when something happens. Every behavior inherits from the Behavior class.
OverrideTo write your own version of an action that a parent class already has.
BehaviorEventAn object that a behavior gets when it runs. It tells the behavior which item it belongs to.
FormBehaviorA behavior made for Forms. It can get the Form and the Page that is showing.
FrameOne drawing of the screen. A Form, like a game, draws many frames every second.
CastTelling Quorum to treat an object as a more specific type, such as treating an Item as a Label.

New Code to Learn

You will be using the following new pieces of code:

New Code to Learn
Quorum CodeCode ExampleExplanation
class NAME is Behaviorclass OutputBehavior is BehaviorMakes a new behavior class.
action Run(BehaviorEvent event)action Run(BehaviorEvent event)Runs once when the behavior starts.
action Update(number seconds)action Update(number seconds)Runs every frame, for behaviors added with AddBehavior.
action IsFinished returns booleanaction IsFinished returns booleanSays whether the behavior is done.
action Disposeaction DisposeRuns once, after the behavior is done.
EVENT:GetItem()event:GetItem()Gets the item the behavior belongs to.
BUTTON:SetBehavior(BEHAVIOR)button:SetBehavior(behavior)Runs the behavior each time the button is pressed.
ITEM:AddBehavior(BEHAVIOR)timer:AddBehavior(countdown)Starts a behavior on an item. It runs until it is finished.
GetPage()Page page = GetPage()In a FormBehavior, gets the Page that is showing.
output TEXToutput "Done"Writes the text in Quorum Studio's output window.

CSTA Standards

This lesson covers the following CSTA K–12 standards:

For teachers · 2026 CSTA K–12 Computer Science Standards

HS-PRO-PD-12

High School · Programming

Create a modular program that uses procedures, external libraries, or objects to improve reusability and readability.

Also in 9 other lessons

HS-PRO-RD-17

High School · Programming

Analyze how a segment of code works, including the role of parameters, return values, and data structures.

Also in 6 other lessons

MS-PRO-PD-12

Middle School · Programming

Use a procedure to structure code for clarity and reusability.

Also in 5 other lessons

MS-PRO-RD-17

Middle School · Programming

Analyze the roles of iteration, selection, variables, and procedures in a segment of code.

Also in 3 other lessons

Every standard, and the lessons that cover it

Explore

In Forms, you used a FormBehavior to respond to a button. FormBehavior is one kind of behavior. In this tutorial, you will explore the Behavior class itself and write your own. You should already know about inheritance, because every behavior inherits from Behavior and replaces, or overrides, some of its actions.

The Behavior class

The Behavior class lives in Libraries.Interface.Behaviors. On its own, it does nothing. You make a new class that inherits from it and override the actions you need. These are its four main actions:

action Run(BehaviorEvent event)
end

action Update(number seconds)
end

action IsFinished returns boolean
    return false
end

action Dispose
end
The four main actions of a Behavior
ActionWhen it runsWhat it is for
RunOnce, when the behavior startsThe main work, or setting things up
UpdateEvery frame, while the behavior is runningChanges that happen bit by bit, like a countdown
IsFinishedEvery frame, before UpdateReturns true when the behavior is done
DisposeOnce, after IsFinished returns trueCleaning up, or showing "done"

The event that Run gets is a BehaviorEvent. Its GetItem action tells you which item the behavior belongs to, such as the button that was pressed.

Two ways a behavior runs

There are two ways to give a behavior to an item. They run the actions differently:

SetBehavior and AddBehavior
SetBehaviorAddBehavior
Used onButtons and other controlsAny item, such as a label or a button
When Run happensEvery time the control is pressedOnce, right away
Update, IsFinished, DisposeNot called by a buttonCalled every frame until IsFinished returns true
Good forReacting to a pressSomething that takes time, like a countdown

You will try both.

A behavior for a button

To start, make a new project in Quorum Studio. Under General, choose App. Then add a new file to the project named OutputBehavior.quorum with this code:

use Libraries.Interface.Behaviors.Behavior
use Libraries.Interface.Events.BehaviorEvent

class OutputBehavior is Behavior
    action Run(BehaviorEvent event)
        output "You pressed " + event:GetItem():GetName()
    end
end

This class overrides only Run. It gets the item that was pressed with event:GetItem(), then its name with GetName(), and writes a message in the output window.

Now replace the code in Main.quorum with this:

use Libraries.Interface.Forms.Form
use Libraries.Interface.Forms.Page
use Libraries.Interface.Controls.Button

Form form
Page page = form:GetMainPage()
page:SetTitle("Behaviors")

Button hello = page:AddButton("Hello")
hello:SetDescription("Says which button you pressed")

Button goodbye = page:AddButton("Goodbye")
goodbye:SetDescription("Says which button you pressed")

OutputBehavior behavior
hello:SetBehavior(behavior)
goodbye:SetBehavior(behavior)

form:Display()

Run the program. Press Tab until the Hello button has the focus, then press Space or Enter, or click it. The output window shows "You pressed Hello". Press Tab to move to the other button and press it. Now the output window shows "You pressed Goodbye". One behavior object serves both buttons, because event:GetItem() tells it which one was pressed. With SetBehavior, a button calls Run each time it is pressed. It doesn't call Update, IsFinished, or Dispose.

Behaviors that change the page

OutputBehavior writes to the output window, which is only for you, the programmer. Most apps change something on the page instead. A FormBehavior is a behavior that can find the page that is showing, with its GetPage action. From the page, it can find any control by its name.

In this program, the Main class is itself a FormBehavior, so it can be the button's behavior, as in the Forms tutorial:

use Libraries.Interface.Forms.Form
use Libraries.Interface.Forms.Page
use Libraries.Interface.Forms.FormBehavior
use Libraries.Interface.Events.BehaviorEvent
use Libraries.Interface.Controls.Button
use Libraries.Game.Graphics.Label

class Main is FormBehavior
    integer presses = 0

    action Main
        Form form
        Page page = form:GetMainPage()
        page:SetTitle("Press Counter")

        Button press = page:AddButton("Press me")
        press:SetDescription("Adds one to the count")
        press:SetBehavior(me)

        page:AddLabel("Count", "You haven't pressed the button yet.")

        form:Display()
    end

    action Run(BehaviorEvent event)
        presses = presses + 1
        Page page = GetPage()
        Label count = page:GetLabel("Count")
        count:SetText("You pressed the button " + presses + " times.")
    end
end

page:AddLabel("Count", ...) gives the label a name, "Count", and the text it shows. In Run, GetPage() gets the page, and GetLabel("Count") finds the label by its name. SetText changes what it says. The variable presses belongs to the Main object, so it keeps its value between presses.

A behavior that takes time

Now you will make a countdown: a label that counts down from 5 seconds, then says "Time is up!". This needs all four actions. Add a new file named CountdownBehavior.quorum:

use Libraries.Interface.Behaviors.Behavior
use Libraries.Interface.Events.BehaviorEvent
use Libraries.Game.Graphics.Label

class CountdownBehavior is Behavior
    Label label = undefined
    number timer = 0
    integer secondsShown = 0

    action Run(BehaviorEvent event)
        label = cast(Label, event:GetItem())
        label:SetText("Seconds left: 5")
    end

    action Update(number seconds)
        timer = timer + seconds
        if label not= undefined and timer >= secondsShown + 1
            secondsShown = secondsShown + 1
            label:SetText("Seconds left: " + (5 - secondsShown))
        end
    end

    action IsFinished returns boolean
        return timer >= 5
    end

    action Dispose
        if label not= undefined
            label:SetText("Time is up!")
        end
    end
end

Here is how each action works:

  • Variables: label remembers the label between actions. It starts as undefined, which means "nothing yet". timer counts the seconds that have passed. secondsShown counts the whole seconds the label has shown.
  • Run: event:GetItem() gives back an Item, the most general kind of object on the screen. To change its text, you need it as a Label, so you cast it. Then the code shows the starting time.
  • Update: seconds is the time since the last frame, usually a tiny fraction of a second. The code adds it to timer. Each time another whole second has passed, it changes the label.
  • IsFinished: returns true once five seconds have passed.
  • Dispose: runs once, after IsFinished returns true. It changes the label to "Time is up!".

Now replace Main.quorum with this program. Its button starts a new countdown on the label each time it is pressed:

use Libraries.Interface.Forms.Form
use Libraries.Interface.Forms.Page
use Libraries.Interface.Forms.FormBehavior
use Libraries.Interface.Events.BehaviorEvent
use Libraries.Interface.Controls.Button
use Libraries.Game.Graphics.Label

class Main is FormBehavior
    action Main
        Form form
        Page page = form:GetMainPage()
        page:SetTitle("Countdown")

        Button start = page:AddButton("Start")
        start:SetDescription("Counts down from 5 seconds")
        start:SetBehavior(me)

        page:AddLabel("Timer", "Press Start to begin.")

        form:Display()
    end

    action Run(BehaviorEvent event)
        Page page = GetPage()
        Label timer = page:GetLabel("Timer")
        if timer not= undefined
            CountdownBehavior countdown
            timer:AddBehavior(countdown)
        end
    end
end

Run it and press Start. The label counts down, one second at a time, then says "Time is up!". With AddBehavior, Run happens right away. After that, on every frame, the Form asks IsFinished. While the answer is false, it calls Update. Once the answer is true, it calls Dispose and removes the behavior.

The line CountdownBehavior countdown is inside Run, so a brand new countdown, with its timer at zero, is made each time the button is pressed. Try pressing the button twice, about two seconds apart. What happens to the label, and why?

Blocks

A shortcut: TimedBehavior

Counting time is so common that Quorum has a behavior that does it for you: TimedBehavior. You give it a number of seconds with SetTimer. Its Update counts down, and its IsFinished returns true when the time is up. Add a file named WaitBehavior.quorum:

use Libraries.Interface.Behaviors.TimedBehavior
use Libraries.Interface.Events.BehaviorEvent
use Libraries.Game.Graphics.Label

class WaitBehavior is TimedBehavior
    Label label = undefined

    on create
        SetTimer(3)
    end

    action Run(BehaviorEvent event)
        label = cast(Label, event:GetItem())
        label:SetText("Wait for it...")
    end

    action Dispose
        if label not= undefined
            label:SetText("Time is up!")
        end
    end
end

WaitBehavior doesn't write Update or IsFinished at all. It uses the ones it inherits from TimedBehavior. To try it, use WaitBehavior instead of CountdownBehavior in Main. If you ever override Update in a TimedBehavior, call the parent's first, with parent:TimedBehavior:Update(seconds), so the timer keeps counting.

Making changes everyone can find

When a behavior changes the page, every person using the app needs a way to find the change. In these programs, the change is in a label's text. On a Form, labels are in the Tab order, so a screen reader user can press Tab from the button to reach the label and hear what it says now. Keep the label close to the button that changes it, so it's easy to find.

A change that is only a color, a movement or a picture is easy to miss, even for people who can see the screen. When a behavior changes something, ask yourself how a person who can't see it would find out. Putting the news in a label's text, or in a control's name or description, is a good way.

Engage

In this activity, you and a partner change and write behaviors, predicting what each change will do before you run it. The goal is to understand that a behavior is code that runs when something happens, and to practice reading code carefully. One of you types while the other reads each line aloud and predicts what it will do; switch roles after each task. First, change CountdownBehavior so it counts down from 10 seconds. Before you run it, agree on every number you need to change. Could you change the class so there is only one number to change?

Next, write a new behavior, CountUpBehavior, that counts up from 0 to 5, one second at a time, and then shows "Done counting". Then add a second button named "Count up" that starts your CountUpBehavior on a second label. To finish, test your program with only the keyboard: can you reach and press both buttons, and can you reach each label with Tab to find out what it says?

Wrap up

You used SetBehavior to react to a press and AddBehavior to make something happen over time. Think of a game or app you know. Find one thing in it that would use SetBehavior and one that would use AddBehavior. Explain your choices to a partner.