When you will run a JavaFX application you must extend the Application
class in your Main class:
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application{ //extends Application
public Main() {
launch(args); //start window
}
@Override
public void start(Stage primaryStage) throws Exception {
//code here
}
}
Now you must override the start
method. In this start
method you have as parameter the Stage primaryStage
, this is your Window. To call thestart
method you must call: launch(args)
in main method.
Now you can add your Code in the start
method.
When you will create your GUI in another class like Contoller than you have different ways to do this.
First we look on the Stage which in the Constructor. To display the stage you first need to set a Scene to the Stage:
stage.setScene(Scene scene);
To create a Stage you must add a Parent
object in the Constructor
new Scene(Parent root);
Some Parent Object are Group
and Region
Further subclasses of Parent
are: Pane
, GridPane
, BorderPane
, Chart
, TableView
, ListView
and much more.
We have a Stage from the Start Method so we now need a Scene
We can create this in the start method and add it to the Stage:
Scene scene = new Scene();
primaryStage.setScene(scene);
This code doesn't run because the Scene()
need a Argument of type Parent
Now we can create our Controller class in which we make our Parent object with all our GUI components. For this we create a Parent object (in this case BorderPane) in our Controller class:
public class Controller {
private final BorderPane borderPane;
public Controller() {
borderPane = new BorderPane();
//gui code here
}
}
Now we can create our gui in the Controller class.
Finnaly we make a function in the Controller class to get this Borderpane for our gui:
public Pane getParentObject(){
return borderPane;
}
In our start
method we now set this Parent object to our Scene:
Controller controller = new Controller();
Scene scene = new Scene(controller.getParentObject());
primaryStage.setScene(scene);
primaryStage.show();
At the end we only need to show our Stage.
I would recommend you to search for some tutorials with JavaFx there are a loot of good video or read tutorials in the Internet
I hope I could help you