Skip to content

Getting Started: Creating Hello World UI

Jeff Martin edited this page Apr 11, 2019 · 17 revisions

Getting Started: Creating a basic UI app

ViewOwner

The top level object in a SnapKit application is usually a subclass of snap.view.ViewOwner. This class contains the following key methods for creating UI, initializing it, updating it from app data and responding to changes:

import snap.view.*;

public class HelloWorld extends ViewOwner {

    /** Create UI here. */
    protected View createUI()  { return new Button("Hello World"); }

    /** Initial UI configuration. */
    protected void initUI()  { getUI().setName("MyButton"); }

    /** Update UI after any user input. */
    protected void resetUI()  { }

    /** Respond to UI. */
    protected void respondUI(ViewEvent anEvent)
    {
        if(anEvent.equals("MyButton"))
            System.out.println("Button was pressed");
    }

    /** Standard main. */
    public static void main(String args[])  { new HelloWorld().setWindowVisible(true); }

}

The createUI() method

In practice this method is rarely needed - most SnapKit UI is defined in UI files in the SnapBuilder application: SnapBuilder. The default implementation of createUI() looks for a file named ClassName.snp in the same directory as the ClassName.java. If found, the UI is loaded and returned by default. A '.snp' file is just an XML file with the UI description, like this:

    <RowView Padding="4,4,4,4">
        <Button Name="MainButton" Title="Press Me" PrefWidth="80" PrefHeight="24" />
    </RowView>

However, sometimes it can be useful to create the UI in code, or load base UI from a .snp file and wrap it in higher level UI, like a TabView.

The initUI() method

The initUI method is useful to load initial values into UI views like ListView or TableView or enable additional events on UI for the ViewOwner to respond to (MousePress, MouseEnter).

    protected void initUI()
    {
        // Configure ListView with color names
        ListView listView = getView("MyListView", ListView.class);
        listView.setItems("Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet");

        // Configure Label to turn blue on mouse-over
        Label myLabel = getView("MyLabel", Label.class);
        enableEvents(myLabel, MousePress);
        myLabel.addEventHandler(e -> myLabel.setFill(Color.BLUE), MouseEnter);
        myLabel.addEventHandler(e -> myLabel.setFill(null), MouseExit);
    }

The resetUI() method

This method is called every time the user interacts with the UI (after respondUI()). It is used to update values in UI, usually with a call to setViewValue("MyTextField", newValue).

The respondUI() method

This method is called every time the user interacts with the UI, like a button press, a textfield change or a ListView selection.

Clone this wiki locally