When reading javafx 8 tutorials, this seems to be the main work flow:
public class Test extends Application{
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(TestFXController.class.getResource("test.fxml"));
Parent root;
try {
root = fxmlLoader.load();
Scene scene = new Scene(root, 1200, 800);
primaryStage.setScene(scene);
primaryStage.show();
TestFXController controller = fxmlLoader.getController();
controller.plotSomething();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let's say that I have an Algorithm which I want to run. After starting the above application I may end up with an interface containing a "run algorithm" button. After pressing the button, an action handler invokes the algorithm. I then have: start java application -> build interface -> press button to solve Algorithm -> display solution. All that separates the graphical stuff from the algorithm is a button. In fact, the graphical interface 'drives' the application in the sense that it is responsible for launching the algorithm. What I would prefer however is something like this:
public class Test2{
public void main(String[] args){
Algorithm alg=new Algorithm();
alg.solve();
GUI gui =new GUI(); //Spawns a Javafx 8 Graphical User Interface
gui.displaySolution(alg.getSolution());
}
}
To me, this seems a lot cleaner? I'm however not sure how to do this with javafx 8, or whether this is even possible? Any examples or references are highly appreciated. What should I put in the GUI class such that it launches a javafx 8 interface? The example in Test2 would also open up possibilities to use a clean Observer Design Pattern like this:
public class Test3{
public void main(String[] args){
Algorithm alg=new Algorithm();
alg.addListener(new GUI()); //Add a Javafx 8 GUI as a listener.
alg.addListener(new TextualLogger());
alg.solve();
}
}
Notice that in the classes Test2 and Test3, the GUI no longer drives the application.
To clarify, my main question would be: what should be the implementation of the GUI class if I would run the code in Test2? Something like this:
public class GUI extends Application{
public GUI(){
//What should I put here? Perhaps launch(new String[]); ?
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(TestFXController.class.getResource("test.fxml"));
Parent root;
try {
root = fxmlLoader.load();
Scene scene = new Scene(root, 1200, 800);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void displaySolution(Solution sol){
...
}
}