Moe February 2016

How to pass a new instance variable to JavaFX Controller using Java 7

For simplicity I have a JavaFX app that allows you to set/get Name from 2 different classes and display the get name on its scene label. This works with no problem, but what I can't do is how to pass a new instance variable from a different class "AnotherClass" to the JavaFX FXML Controller?

From the FXML Controller I did the following to reference the new instance variable.

public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("Hello ");
        Variable var = new Variable();
        BaseLine base = new BaseLine();

        var.setName("Rob");
        base.printout(var);
       label.setText(base.printout(var));
        label.setText(label.getText() + base.set(var));
    }

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

}

As you can see in the FXML controller I have created 2 instances of the 2 classes below that handle the set/get Name

public class BaseLine {

    String printout(Variable sg){
        System.out.println("My Name is: "+ sg.getName());
        return sg.getName();
    }

    String set(Variable sg){
       sg.setName("Bob");
        return sg.getName();
    }

public class Variable {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Now here is my question, from the AnotherClass how can I pass a new instance to JavaFXML Controller?

public class AnotherClass {
FXMLDocumentController newInstance = new  FXMLDocumentController();

}

And how can I accept the new creation of this instance inside my FXMLDocumentController?

Answers


Smutje February 2016

Refactor FXMLDocumentController so that it stores var as a mutable field, refactor the label-setting code to a method and add the following somewhere in AnotherClass:

Variable variable = new Variable();
variable.setName("Test");
this.newInstance.setVariable(variable);

Post Status

Asked in February 2016
Viewed 2,956 times
Voted 10
Answered 1 times

Search




Leave an answer