Building GUI with JavaFX

Anna Scott
2 min readJun 27, 2021

In the short post:

there are steps to start designing JavaFX application. The short application in the post does not go past displaying user interface. In order, for user interface to perform as desired, user interface components need to have event handlers attached to them. Whenever an action performed on interface component (for example button is pressed), event handler attached to that component is called and the written functionality is executed. Usually event handler changes the state of object. Let’s look at the following interface:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

@Override
public void start(Stage window){
window.setTitle("GUI");
//GUI elements
Label name = new Label("Please, your name");
TextField inputName = new TextField();
Button buttonName = new Button("Done");
Label greeting = new Label();

//container for GUI
VBox container = new VBox();

container.getChildren().add(name);
container.getChildren().add(inputName);
container.getChildren().add(buttonName);
container.getChildren().add(greeting);

Scene scene = new Scene(container);

window.setScene(scene);
window.show();

}

public static void main(String[] args) {

launch(Main.class);
}
}

Output of this application:

We would like the input of the text field (name of user) used in greeting when button is pressed. We can do that with the object implementing the EventHandler interface.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

@Override
public void start(Stage window){
window.setTitle("GUI");
//GUI elements
Label name = new Label("Please, your name");
TextField inputName = new TextField();
Button buttonName = new Button("Done");
Label greeting = new Label();

//implementin EventHandler
buttonName.setOnAction(event -> greeting.setText("Greetings " + inputName.getText() + "!!!"));

//container for GUI
VBox container = new VBox();

container.getChildren().add(name);
container.getChildren().add(inputName);
container.getChildren().add(buttonName);
container.getChildren().add(greeting);

Scene scene = new Scene(container);

window.setScene(scene);
window.show();

}

public static void main(String[] args) {

launch(Main.class);
}
}

Output:

Happy coding my friends!

--

--