I want to seperate a JavaFX project to model, view and controller. I use netbeans when creating a JavaFX application. But I want the code seperate, an own GUI, own logic and a Main class just to start the application (I want 3 seperate classes). But I am not able to solve this problem. The automatic created code looks like this:
package at.wueschn.www;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Here is a "Java-only" (i.e. no FXML) example of MVC. Note that there are many different variants of MVC, which is a very loosely-defined pattern. This is a kind of "classical" variant: the model has no knowledge of the view(s) or controller(s) (which is the common theme to all MVC-type designs), the controller has a reference to the model and invokes methods on it, implementing some simple logic, and the view has a reference to both the model and controller; observing the model and updating the view components when the data changes, and invoking methods on the controller in response to user input. Other variants of this pattern (MVVM, MVP, etc) typically vary in the relationship between the view and the controller.
This simple application implements a very basic calculator, which simply knows how to add two single-digit integers.
The model:
The controller:
The view:
and finally the "main" class which creates each piece and displays the view in a window:
If you are using
NetBeans
, first chooseFile -> New Project
. ThenJavaFX -> JavaFX FXML Application
Note: This is a basic
MVC
setup. You could do all of this using pure code. James_D could probably help you with more advancedMCV
ideas.Note: If you are going to take this simple approach, I suggest you download
SceneBuilder
to help you with the view. Tutorial