Using a JavaFx application instance from another class

后端 未结 1 1612
清歌不尽
清歌不尽 2021-01-03 09:58

I have a MainWindowFx class like below. It basically creates a simple JavaFX GUI.

package drawappfx;


import javafx.stage.Stage;
import javafx.         


        
相关标签:
1条回答
  • 2021-01-03 09:58

    I've had this problem several times and there is a fairly easy way to resolve it.

    First of all let me introduce you to the Mediator pattern, basically you want to create a class that has the relationship with all your GUI classes

    (I.e the different GUI classes do not have their own instance of each other instead all of them has the same reference to the Mediator).

    That was a sidetrack now to your question.

    In order to change window you need to pass the Stage of which the new window should be placed upon because of this your code needs only a minor change:

    Now I do not often do this but in your case, I will make an exception the following code consists of a class that you can "Copy Paste" into your program and use that will fix the problem after the code I will explain exactly what I did:

    Mediator

    public class Mediator extends Application {
    
        private DrawAppFx daf;
        private MainWindowFX mainWindow;
        private Stage primaryStage;
        public Mediator(){
            daf = new DrawAppFx(this);
            mainWindow = new MainWindowFx(this);
    
        }
        public static void main(String[] args){
            launch(args);
        }
        @Override
        public void start(Stage stage) throws Exception {
            primaryStage = stage;
            mainWindow.start(primaryStage);
        }
        public void changeToDaf(){
            daf.start(primaryStage);
        }
    }
    

    Now each of the DrawAppFx and MainWindowFx must have a constructor that passes a Mediator object and therefore have a "Has-a" relationship with the mediator

    The reason behind this is that the mediator pattern is now in control and should you create more windows it is easy to implement just add them to the mediator and add a method for which the mediator can change to that window.

    0 讨论(0)
提交回复
热议问题