jeudi 21 octobre 2021

Best design pattern to make panes communicate with each other javafx

What I'm trying to achieve is to guarantee a communication between different panes in my program, this picture is a simple representation of what I'm willing to achieve

enter image description here

there is a scene with the main AnchorPane (I'm using FXML), and it has a changeable pane zone in the middle (it changes using the buttons on the left), but I want to control as an example the text label on the top right side ("Text in Main Scene"), using Pane 1 (PS: Pane 1 has another controller that is different from the one used in the main AnchorPane).

I achieved that using SingleTon design pattern, but I'm wondering if there is a more elegant way to achieve that.

My code :

SingleTon class :

 public class SingleTon {

 static SingleTon singleTon = new SingleTon();        

        MainSceneController mainSceneController ;
    
        Pane1Controller pane1Controller;
        
        public Scene loadMainScene() throws IOException {
            mainSceneController = new MainSceneController ();
            FXMLLoader fxmlLoader = new FXMLLoader(MainSceneController.class.getResource("mainAnchorPane.fxml"));
            fxmlLoader.setController(mainSceneController );
            return new Scene(fxmlLoader.load());
        }
        
        public MainSceneController getMainSceneController (){
            return mainSceneController ;
        }
        
        
    }

Main AnchorPane controller :

   public class MainSceneController{
    @FXML
    private Label text;


    public Label getLabel(){
        return text;
    }
}

Pane1 controller :

public class Pane1Controller {

    public void changeTextOfMaineAnchorPane(){
        SingleTon singleTon =  SingleTon.singleTon;

        singleTon.getHelloController().getLabel().setText("change text");
    }
}

Aucun commentaire:

Enregistrer un commentaire