Kotlinlearncs.online LogoJava

    FXML - FX Markup Language

    In English grammar, an imperative sentence is a sentence that gives instructions that express a command. With imperative programming we give step-by-step instructions to the compiler for how it should do something.

    A declarative sentence is a sentence of the form of a statement. Declarative sentences describe what is true. Similarly, with declarative programming we write code that describes what we want but not necessarily how to get it.

    Imperative GUI Layout
    Imperative GUI Layout

    We can create a simple window layout

    Step through creating a GUI with a label and a button in a VBox.

    Here we tell the compiler to:

    1. Create a VBox object.
    2. Create a Label object.
    3. Create a Button object.
    4. Attach the handleClickMe() method as a listener to the button.
    @Override
    public void start(Stage stage) {
    Pane root = new VBox();
    Label message = new Label("Here is some text");
    Button clickMe = new Button("Click Me");
    clickMe.setOnAction(this::handleClickMe);
    stage.setTitle("Imperative GUI");
    stage.setScene(new Scene(root, 400, 300);
    stage.show();
    }

    Declarative GUI Layout
    Declarative GUI Layout

    Instead of detailing the creation of each element in our UI and providing instructions for how to connect them together to create the layout, we declare what we want the layout to look like in an FXML file. We then rely on the FXMLLoader class to read in the FXML file and instantiate the needed UI objects and connect them together.

    While hand-editing small FXML files is perfectly doable, many find it more efficient to use a graphical tool to generate the FXML file. Scene Builder can be used to create FXML files that describe the desired layout of our programs.

    Homework
    Homework

    Use Scene Builder to create a GUI for a simple calculator that includes buttons for all digits as well as add, subtract, multiply, divide, clear, and equals. Experiment with different layout containers to produce a pleasing and functional appearance.

    More Practice

    Need more practice? Head over to the practice page.