Code

Now that the library is installed, it's time to write some code. The following sample is andlabs UI equivalent of the hello world example we used in the Chapter 4, Walk - Building Graphical Windows Applications. Start by entering the following code into a new file, named hello.go:

package main

import "github.com/andlabs/ui"

func main() {
err := ui.Main(func() {
window := ui.NewWindow("Hello", 100, 50, false)
window.SetMargined(true)
window.OnClosing(func(*ui.Window) bool {
ui.Quit()
return true
})

button := ui.NewButton("Quit")
button.OnClicked(func(*ui.Button) {
ui.Quit()
})
box := ui.NewVerticalBox()
box.Append(ui.NewLabel("Hello World!"), false)
box.Append(button, false)

window.SetChild(box)
window.Show()
})
if err != nil {
panic(err)
}
}

This code is pretty straightforward, but there are a few things that we should cover, so let's step through it. As usual, for a simple graphical Go app, we are using the main package and importing the toolkit library, before defining the main() function. We then call the main entry point for an andlabs UI application, ui.Main(), which takes a single function that will build and show the app's GUI. If an error occurred, we cause the binary to panic, as the interface couldn't be loaded.

In our user interface code, we first set up a window with ui.NewWindow(), with a title and a default size, and the final parameter indicates whether the window should have a menu bar. We turn on the default margin (padding) and assign a closing function to exit the app by calling ui.Quit(). Next, a new button is created with ui.NewButton(), labelled Quit, that also exits the application when clicked. These components are laid out using a container with ui.NewVerticalBox(). A Hello World! label and the Quit button are both added. The Append() method of ui.Box takes a Boolean parameter, stretchy—if this is set to true, the component will expand to fill the available space. Last, we set the content of the window with SetChild() and show it using Show().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.171.51