Java FX: Hello World!
Having mostly finished building my Java Tic Tac Toe console application, my next challenge is to build a GUI. Pretty much all my previous experience has been web based, and mostly JavaScript. Although now Electron makes it possible to build GUI’s in web tech, GUI’s have largely seemed well outside the scope of my experience. But now I’m learning Java, it’s all about to change!
JavaFX vs Swing
I was given free choice of which Java GUI library to use. But was pointed in the direction of JavaFX and Swing. After a quick google it appears that JavaFX is the newer library, and for that reason alone, I decided to use it.
Getting started
I started with the “Getting Started with JavaFX” Oracle docs Hello World example. Which is a nice simple introduction to the basic structure of a JavaFX application, and has the added benefit of being able to get something up and working with minimal effort. Given the brevity and simplicity of the tutorial, there’s not much point summarising it here, but the biggest take-away for me, was understanding the hierarchical node structure of a JavaFX application:
- The
Stage: the top level container, which is injected into thestartmethod, and represents the familiar open, close window inside of which your application exists. - The
Scene: the container for all content inside theStage - The
StackPane: a re-sizeable layout node, which (in the Hello World Example), is the root node inside the Scene - The
Button: a standard GUI button, which has various helpful methods for setting text and event handlers
A bit like the DOM
With my web background, this kind of node based structure feels very familiar. For example, adding the Button to the StackPane, looks like this:
Button button = new Button();
StackPane root = new StackPane();
root.getChildren().add(button);The similarity goes even further, once I worked out (thanks to IntelliJ’s refactoring prompts), that the Button event handler method can take a lambda expression, so creating a button which, on click, prints “Hello World!” to the console looks like this:
Button button = new Button();
button.setText("Say 'Hello World!'");
button.setOnAction(event -> System.out.println("Hello World!"));Contrast with the equivalent DOM/JavaScript code:
const button = document.createElement('button');
button.appendChild(document.createTextNode("Say 'Hello World!'"));
button.onClick(event -> console.log('Hello World!'));Whilst the JavaScript/DOM example has some additional complexity in setting the button text, the underlying node structure is remarkably similar.
My next challenge will be to create a Tic Tac Toe board, so I’ll soon see if this similarity goes beyond the superficiality of a Hello World example. But, at least for now, it gives me a warming sense of familiarity.