I want to click a column and send the cell index to a new stage. But I can\'t pass my parameter (int clickIndex) to another controller EditClientControlle
All you need to do is get an instance of your second controller:
EditClientController controller=fxmlLoader.<EditClientController>getController();
and you now will be able to send the required index:
controller.setIndex(clickIndex);
This is all that's required:
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("editClient.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
EditClientController controller=fxmlLoader.<EditClientController>getController();
controller.setIndex(clickIndex);
Stage stage = new Stage();
stage.setTitle("Edytuj klienta");
stage.setScene(new Scene(root1));
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
EDIT
As clickIndex will be sent after the second controller is initialized, this value won't be available on Initialize.
A valid way to solve this is adding a listener to changes:
private IntegerProperty index = new SimpleIntegerProperty(-1);
public void setIndex(int index){
this.index.set(index);
}
public int getIndex(){
return index.get();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
index.addListener((ob,n,n1)->{
city.setText(tablica.get(n1.intValue()).getRCity());
});
}
When moving from one controller to another(one view to another), you could initialize the EditClientController with the required parameters
Eg:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("editClient.fxml"));
EditClientController ctrl = new EditClientController();
ctrl.setCellIndex(id);
fxmlLoader.setController(ctrl);
If you have specified the controller in the fxml file, the you could use:
editWrapper.getCurrentController().setCellIndex(id);
where editControllerWrapper is a class that loads the new view and has a method getCurrentController that returns an instance of javafx controller.
Eg: public class EditControllerWrapper {
private Parent root;
public EditControllerWrapper () {
try
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("editClient.fxml"),
...
} catch (Exception e) {
...
}
}
public <T> T getCurrentController () {
return loader.getController();
}
If you want to specify the controller in the FXML file (so you can't use Deepak's answer) and you want to access the index in the initialize() method (so you can't use José's answer), you can use a controller factory:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("editClient.fxml"));
fxmlLoader.setControllerFactory(new Callback<Class<?>, Object>() {
@Override
public Object call(Class<?> controllerClass) {
if (controllerClass == EditClientController.class) {
EditClientController controller = new EditClientController()
controller.setIndex(clickIndex);
return controller ;
} else {
try {
return controllerClass.newInstance();
} catch (Exception exc) {
throw new RuntimeException(exc); // just bail
}
}
}
});
Parent root1 = fxmlLoader.load();