javafx how to transfer variable values from one controller to another


Question

i am new to javafx and i want to transfer variable values from one controller to another and i have no idea how to do this. so please help me.

for example:

i want to display username from first login window to second dashboard window so what should i do to save userid in one variable and send it to second window and display there in a label.

code test:

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;

/**
 * FXML Controller class
 *
 * @author wabcon
 */
public class AdmissionController implements Initializable {

int userid=0;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    userid=10001;

    }    

}

how could i send this userid to next window controller. please help me. Thank you.

1
1
6/12/2014 5:55:46 PM

Accepted Answer

I am assuming you are doing this for a custom component.

So, you create a class for your custom component and set that class as the controller:

public class CustomControl extends AnchorPane implements Initializable {
    String customId;

    public CustomControl() {
        //if you want to set a FXML
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/res/customControl.fxml"));
        //Defines this class as the controller
        fxmlLoader.setRoot(this);
        //this.getStylesheets().add("/res/style.css"); <- if you want to set a css
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }

    }
        public String getCustomId() {
            return customId;
        }
    public void setCustomId(String customId) {
        return this.customId = customId;
    }
    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
          //Initializes the controller
    }
}

On your MainController:

CustomControl c = new CustomControl();
c.setCustomId("StackOverflow");
1
6/13/2014 6:43:08 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon