Skip to content

Instantly share code, notes, and snippets.

@n2o
Last active June 29, 2017 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n2o/193a1ac8930019f6f4bda1823ccf663c to your computer and use it in GitHub Desktop.
Save n2o/193a1ac8930019f6f4bda1823ccf663c to your computer and use it in GitHub Desktop.
Professional Programming: Results of practical exercises, week 11: JavaFX

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!");
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment