Counter Tutorial with Gtk and GNU Smalltalk

Hi,

In this little tutorial we will build a simple UI. The counter tutorial is just a window with two buttons and a label;
we will see how to add widgets in the main window and how to handle the Gtk events.


The Model

First create a counter class, with an instance variable counter, a method which sets the initial value of the counter, an incrementor and decrementor methods with an converstion method that convert the counter as a string.

" Counter class "

Object subclass: Counter [
    | counter |

    counter: anInteger [
       " setter "

        counter := anInteger
    ]

    counterString [
       " return the counter value as a string "

        ^ counter asString
    ]

    increment [
        " increment the counter and signal that the value as changed "

        counter := counter + 1.
        self changed: #counterString
    ]

    decrement [
        " decrement the counter and signal that the value as changed "

        counter := counter - 1.
        self changed: #counterString
    ]
]


The User Interface

Now we will create the application window and the differents widgets inside it:

    | b1 b2 counter label frame window |

    " The window "
    window := GtkTools GtkMainWindow new.

    " The counter with an initial value set to 0 "
    counter := Counter new
                    counter: 0;
                    yourself.

    " The layout where widgets will be displayed "
    frame := GTK GtkFixed new.

    " A new button "
    b1 := GTK GtkButton labeled: '+'.

  " Send the increment message to counter when the user click 
    on the button "
    b1 onClick: #increment to: counter.

   " Add the button to the frame "
    frame at: 50@20 put: b1.

    " A new button "
    b2 := GTK GtkButton labeled: '-'.

   " Send the decrement message to counter when the user click 
     on the button "
    b2 onClick: #decrement to: counter.

    " Add the button to the frame "
    frame at: 50@80 put: b2.

    " The label "
    label := GTK GtkLabel new: '0'.

    " Update the label when counter update its value "
    label refreshFrom: #counterString for: counter.
    frame at: 190@58 put: label.

    window
        centralWidget: frame;
        title: 'simple';
        statusMessage: 'Simple GTK Application';

    " Set the application size "
        resize: 230@150;

    " Set the application icon "
        icon: (GTK.GdkPixbuf fromFile: 'visualgst.png');
        showAll.
    counter increment.
    GTK Gtk main

User login