Go to the first, previous, next, last section, table of contents.

Creating and using ToggleButtons

To create a toggle button requires just the labels for the on and off states:


toggleButton :: Picture -> Picture -> Component (Toggle Bool, DisplayHandle)

main =
 mkDC [] >>= \dc ->
  toggleButton (text "Off") (text "On")     dc >>= \ (btn1, btn1_dh) ->
  toggleButton (text "Start") (text "Stop") dc >>= \ (btn2, btn2_dh) ->
 realiseDH dc (hbox [btn1_dh, btn2_dh])        >>
 return ()

Given the labels to use, a Toggle instance is created (see See section Boxes and glue abstraction for how the hbox combinator used above works).

Two toggle buttons

To catch the user's click on a button, the operation waitToggleClick comes in useful:


waitToggleClick :: Toggle a -> IO a

main =
  ... as above ..
  waitToggleClick btn1 >>
  return ()

It blocks until the next time the user presses the toggle, returning a boolean to indicate the state of the the Toggle. Using this operation together with setButtonLabel, a counter button can be created:


counterBtn :: Toggle Bool -> IO ()
counterBtn btn =
 newEmptyMVar             >>= \ lock ->
 setToggleValue btn False >>
 forkIO (counter btn 0)   >>
 loopIO (
    waitToggleClick btn      >>= \flg ->
    if flg then
      {- allow counter to run -}
      putMVar lock ()
    else
      {- block counter -}
      takeMVar lock)
 where
  counter lock btn v =
       readMVar lock >>
       setToggleLabel btn True  (text (show v)) >>
       setToggleLabel btn False (text (show v)) >>
       counter lock btn (v+1)

main =
 wopen [] (toggleButton (text "0") (text "0")) >>= \(btn,_) ->
 counterBtn btn

Counter button


Go to the first, previous, next, last section, table of contents.