This week we started with JavaFX and created a simple HelloWorld-Application. Later, we created a more advanced UI with the Gluon SceneBuilder. But I will only upload our hello-world example, since working with the SceneBuilder is straightforward.
This is a gradle project and the source code is based on the standard JavaFX template by IntelliJ.
// build.gradle
apply plugin: 'java'
apply plugin: 'application'
repositories {
jcenter()
}
dependencies {
testCompile 'junit:junit:4.12'
}
mainClassName = 'Main'
Bootstrapping the JavaFX application with a primary stage:
// src/main/java/Main.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello, World!");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
}
FXML file, which needs to be located in a separate resources directory:
<!-- src/main/resources/sample.fxml -->
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.VBox?>
<GridPane fx:controller="Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center"
hgap="10" vgap="10">
<VBox alignment="center">
<Label text="Hello, World!" fx:id="myLabel"/>
<Button text="Click me" onMouseClicked="#clickButton"/>
</VBox>
</GridPane>
And our Controller-Class for the logic in our stages:
// src/main/java/Controller.java
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class Controller {
@FXML
public Label myLabel;
public void clickButton() {
System.out.println("Button clicked!");
myLabel.setText("OMG, she pushed the button!");
}
}