Make a Program – JavaFX Tutorial: Make a Window
For instructions on setting up Eclipse (our IDE), click here.
Start by making a new Java project in Eclipse by using File -> New -> Java Project. After that, create a new class named Main and open it. Create the entry point to our program as such:
1 2 3 |
public static void main (String[] args) { } |
Next we need to declare two variables, a BorderPane and a Scene:
1 2 |
private BorderPane layout; private Scene scene; |
In order to access these class types, we’ll need to make our Main class extend Application, which is a JavaFX interface. We should now have a class like this:
1 2 3 4 5 6 7 8 9 |
public class Main extends Application { private BorderPane layout; private Scene scene; public static void main (String[] args) { } } |
Next we can import the Application, BorderPane and Scene resources by hovering over them and selecting the import option, or by hitting Ctrl+Shift+O. If you are unable to import these classes, it’s possible that your version of Java requires a custom access modifier in order to use JavaFX. Please check the video embedded above for instructions on how to enable that.
Main will now ask you to implement the start() method required by the Application interface. Go ahead and do that and then initialize the scene and layout variables within the method. The Scene() arguments are a layout instance, window width and window height.
1 2 3 4 |
@Override public void start(Stage window) throws Exception { layout = new BorderPane(); scene = new Scene(layout, 450, 80); |
Add the following line to your main() method in order to initialize the JavaFX calls.
1 |
launch(args); |
Finally, at the bottom of the start() method, you will need to set the scene of the passed Stage with .setScene(scene) and then make a call to window.show() at the bottom of the method.
If you found this tutorial helpful, consider showing your support here.
Current Patreon supporters at the Source Code tier and up can see the entire source code right below this line: (Login with your Patreon credentials here)