smalltalk Button event handling
Asked Answered
N

2

6

I am new with Squeak Smalltalk. How I can catch a button click event and execute some code when the button is clicked.

I tried this code but it doesn't work!

I created a new Button Class:

SimpleButtonMorph subclass: #ButtonTest
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'test'

Inside this class I write this method:

handleMouseDown: event
^ true.

I want to use the button inside another Morph, so i created new Morph class:

RectangleMorph subclass: #RectangleMorphTest
instanceVariableNames: 'textField button stringLabel mouseAction'
classVariableNames: ''
poolDictionaries: ''
category: 'test'

and inside Initialize method i compose buttonMorph inside RectangleMorph, The initialize method for rectangleMorph:

initialize  
super initialize.
self bounds: ((0@0) extent: (400@400)).
self color: Color gray.

textField := TextFieldMorph new. 
textField color: Color lightYellow.
textField contents: 'text'.
textField bounds: ((25@25) extent: (300@75)).

button := ButtonTest new.
button borderWidth: 2.
button bounds: ((150@150) extent: (200@200)).
button label: 'print text'.
button target: button.  
button mouseDownOn: #yellowButtonPressed  event: [Transcript show: 'hello'].

stringLabel := StringMorph new contents: 'This is a string'.
stringLabel bounds:  ((150@180) extent: (200@200)).

self addMorph: textField.
self addMorph: button.
self addMorph: stringLabel.

Question

I tried to handle a Button event inside RectangleMorph, but it didn't work. So how I can handle a Button click event inside the RectangleMorph?

Nigrify answered 12/12, 2015 at 19:46 Comment(2)
With True (using an upper-case T), you refer to the subclass of Boolean that implements truthy behavior. Instead, you likely want to refer to true (using a lower-case t), the single instance of True.Chil
How can I make Action inside RectangleMorphTest which composed Button when the button clicked ?!Nigrify
C
3

Searching for SimpleButtonMorph on the http://wiki.squeak.org/squeak gives you a number of hits.

Some examples how to use the button class here

You basically have to define a target for the button and an action selector. The target may be a block of code and the action selector the method #value you sent to the block.

So you have

  button target: [Transcript show: 'hello'].

And then

  button actionSelector: #value.

See also

Chrestomathy answered 16/12, 2015 at 6:10 Comment(0)
V
2

I add a simple working snippet that maybe be useful for beginners. Tested in Squeak 5.2.

SimpleButtonMorph new
  target: [Transcript show: 'Hello World !'; cr ];
  label: 'Print something classic ...';
  actionSelector: #value;
  openInWorld.
Valois answered 11/8, 2019 at 1:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.