Pass variable between windows javaFX

2

I am passing a variable from window "A" to window "B". So far so good. The problem starts when in window "B" I try to access the variable when the window starts. Past value does not exist. Ex. My code. Window "A"

 FXMLLoader loader = new FXMLLoader();
            AnchorPane root = loader.load(getClass().getResource("/gescomp/iniciarProva.fxml").openStream());
            IniciarProvaController np = (IniciarProvaController) loader.getController();
            Stage stage = new Stage();
            stage.setTitle("Inicio");
            stage.setScene(new Scene(root, 1000, 550));
            stage.setResizable(false);
            np.id = 33;
            stage.show();

Window "B"

 public int id;

@Override
public void initialize(URL url, ResourceBundle rb) {
   System.out.println("<< " + id + " >>");
}

It should "print" 33, but it does not show anything. If you put a button and when you click to print the variable already gives!

What am I doing wrong? How can I fix the problem?

    
asked by anonymous 08.02.2017 / 17:38

1 answer

2

This is because you are setting the controller in your fxml file, so the initialize(URL location, ResourceBundle resources) method is evoked during the call of the load method of the FXMLLoader class. That is, before you assign the value to variable id . In your case, what happens is this:

FXMLLoader loader = new FXMLLoader();
AnchorPane root = loader.load(getClass().getResource("/gescomp/iniciarProva.fxml")
                        .openStream());    //Aqui o método initialize já foi evocado
IniciarProvaController np = (IniciarProvaController) loader.getController();
//resto do código
np.id = 33; //Nada acontece
stage.show();

To resolve this, you must remove the reference to the controller in your FXML file and set the controller programmatically. Example:

Create a constructor that receives a int in its class IniciarProvaController :

public class IniciarProvaController  implements Initializable {

    private int id;

    //O resto dos seus atributos

    public IniciarProvaController(int id) { 
        this.id = id;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        System.out.println("<< " + id + " >>");
    }

    //O resto dos seus métodos
}

Set the controller to fxml as follows:

FXMLLoader loader = new FXMLLoader(getClass().getResource("/gescomp/iniciarProva.fxml").openStream());
loader.setController(new IniciarProvaController(33));
Parent root = loader.load();;
Stage stage = new Stage();
stage.setTitle("Inicio");
stage.setScene(new Scene(root, 1000, 550));
stage.setResizable(false);
stage.show();
    
08.02.2017 / 18:36