Search code examples
javajavafxscene

Accessing fxml controller's method from fxml loader


What I want to do is if the size of the scene (the window of the application) is resized, I want to resize the contents inside the window accordingly. I have posted my code which I have done till now

The loader class

public class ResizingButtons extends Application {

@Override

public void start(Stage stage) throws Exception {

    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    scene.widthProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            try{
            System.out.println("Scene Width Property is " + scene.getWidth());
            }
            catch(Exception e){
                System.out.println("Error in width listener of scene" +e.getMessage());
            }
        }
    });   
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
  }
}

And this is the controller of the FXMLDocument.fxml fxml class

public class FXMLDocumentController implements Initializable {

@FXML
public Button btn1;

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}    

public void changeBtnSize(){
    btn1.setPrefHeight(200);
    btn1.setStyle("-fx-background-color:red");
  }
}

When the size of the window is resized, I want to access changeBtnSize() method of the controller class.


Solution

  • You can get controller instance from FXMLLoader. Refactor your code like so:

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml")); // Use loader instance
        Parent root = loader.load();
        FXMLDocumentController controller = loader.getController(); // Now you have controller refference here
        //add your listener, feel free to use your controller inside listener implementation
    }