About this series
Since Swing has not the best look and feel, Oracle planned to invent a new graphical user interface. This is where JavaFX comes into play.
This series will cover the basics of JavaFX with some additions of usefull features.
Video
[embedyt]https://www.youtube.com/watch?v=EEcpMTpaWhs[/embedyt]
Content
In order to use JavaFX we need to create a class that inherits from javafx.application.Application:
public class FirstFX extends Application {
The abstract class requires the implementation of them start(Stage primaryStage) method:
import javafx.stage.Stage; /*..*/ @Override public void start(Stage primaryStage) {
This will be the entry point for JavaFX. However, we still need a main method for Java. Here we will now call JavaFX by using the launch(String… args) method. We can just pass through the arguments we received in the main method:
public static void main(String[] args) { launch(args); }
Once JavaFX was called, we end up in our start method. JavaFX has already created an empty Stage which is passed into the start method. A stage is comparable to a JFrame and represents a window that hold our components. We can take a look at the stage by making it visible (just like .setVisible(true) in Swing):
stage.show();
Let’s create some elements and add them to our stage:
import javafx.scene.control.Button; import javafx.scene.control.Label; /*..*/ Label lb_text = new Label("Some Text"); Button btn_click = new Button("Click it");
Just like in Swing, we will make use of predefined layouts. In this example we will use the VBox. This will be our root element:
import javafx.scene.layout.VBox; /*..*/ VBox root = new VBox();
And we will fill the box:
root.getChildren().addAll(lb_text, btn_click);
You can not directly add the VBox onto the stage. It requires a Scene which is just like a JPanel.
import javafx.scene.Scene; /*..*/ Scene scene = new Scene(root, 500, 500);
The first parameter defines the root which will be added to the scene. The other parameters define the size of the scene.
You can set or change the active Scene on a Stage at every time:
stage.setScene(scene);
For now, we have a windows that contains a label and a button. Now we will add an action to the button:
import javafx.event.ActionEvent; import javafx.event.EventHandler; /*..*/ btn_click.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { // Action goes here } });
In here we can now add something like that:
lb_text.setText("New Text");
That’s all for the first part. You can find the complete source-code on GitHub: FirstFX.java
If you have any questions feel free to leave a comment.