NCSSS 2018 JavaFX Workshop

Widgets

Project 1: We are going to build this.

picture of project1

Grab yourself a copy of Template.java and add these constructor calls to the start method. Change its name to Widget.java and update the class names in the file so it compiles.

1. Create buttons The Button class has exactly the constructor you might expect. In our sample app, we will make two buttons.

Button putText = new Button("Put Text");
Button quitButton = new Button("Quit");

The string argument is the text that goes on button.

2. Create a TextField We will do this with the default constructor.

TextField tf = new TextField();

3. Choose a layout and get our widgets in it We will put this all in a VBox Later, we can change this and see other ways of positioning items.

VBox tf = new VBox();

Uh oh, the Import Police!!! Let us import the right stuff. Being old Java hands, you know how to find the fully-qualified name of a class.

import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;

Now compile. You won't see anything new if you run the application. Nothing has been added to the empty stage. First, let's get the widgets into the VBox. The call to vb.getChildren() returns an ObservableList, to which we add our stuff.

vb.getChildren().add(tf);
vb.getChildren().add(putText);
vb.getChildren().add(quitButton);

Set the scene and put it in the Stage.

 primary.setScene(new Scene(vb, 400,400));

If your program is giving you agita, you can download the whole thing here: Widget.java.

You have now completed the first project.

Exercise Try this now. Change the VBox to eachof these and observe the behavior.

Here is the scene graph for our GUI.

             --------------------------
             | new Scene(vb, 400, 400)|
             --------------------------
                         |
             --------------------------
             | new VBox();            |
             --------------------------
            /            |            \
           /             |             \
    -------------  -------------  --------------
    |  tf       |  | putText   |  |quitButton  |
    -------------  -------------  --------------