| 1 | = Gtk Simple Window = |
| 2 | |
| 3 | The simplest Gtk program displays a window which closes when told to. |
| 4 | |
| 5 | [[Image(window.png)]] |
| 6 | |
| 7 | The following program is in two parts: |
| 8 | |
| 9 | a. The class `MyWindow` will be the main window for the application. `MyWindow` inherits from the Gtk `Window` class, and the `init` method initialises its parent with the given title. |
| 10 | * `.setDefaultSize` is called to create a sensible size for the window |
| 11 | * `listen` is used to attach a method to the `deleteEvent`, called when the user clicks the close window button. |
| 12 | |
| 13 | b. The `main` method in `MainProgram` goes through four stages to create and display a Gtk application: |
| 14 | 1. start the graphical application |
| 15 | 2. create an instance of the main window |
| 16 | 3. request all widgets in the main window to show themselves |
| 17 | 4. finally, run the graphical application |
| 18 | |
| 19 | {{{ |
| 20 | #!cobra |
| 21 | # @args -pkg:gtk-sharp-2.0 # remove initial '#' |
| 22 | |
| 23 | use Gtk |
| 24 | |
| 25 | class MyWindow inherits Window |
| 26 | |
| 27 | def onDeleteEvent(obj, args as DeleteEventArgs) |
| 28 | """ |
| 29 | This method is tied to the deleteEvent, and is called when the close |
| 30 | button is clicked. It causes the application to quit. |
| 31 | """ |
| 32 | Application.quit |
| 33 | |
| 34 | cue init(title as String) |
| 35 | # pass the title to the parent window |
| 36 | base.init(title) |
| 37 | # set a size for our window |
| 38 | .setDefaultSize(300, 200) |
| 39 | # register method to handle the close event |
| 40 | listen .deleteEvent, ref .onDeleteEvent |
| 41 | |
| 42 | class MainProgram |
| 43 | def main |
| 44 | # initialise the application |
| 45 | Application.init |
| 46 | # create an instance of our main window |
| 47 | window = MyWindow("Cobra's First Window") |
| 48 | # show all the widgets within the window |
| 49 | window.showAll |
| 50 | # start running the application |
| 51 | Application.run |
| 52 | }}} |