Pass variable between javafx windows

Asked

Viewed 1,312 times

2

I’m passing a variable from window "A" to window "B". So far so good. The problem starts when in the "B" window I try to access the variable when the window starts. The value passed does not exist. Ex is 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 shows nothing. If you put a button and click print the variable already gives!

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

1 answer

2


This is because you are setting the controller in your file fxml, thus the method initialize(URL location, ResourceBundle resources) is evoked during the method call load class FXMLLoader. That is, before you assign the value to the variableid. 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 one int in your 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 thus:

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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.