How to access JavaFX components in the constructor of Controller Class


Question

I am loading an FXML file the following way

        FXMLLoader loader = new FXMLLoader(getClass().getResource("register.fxml"));
        Controller c = new Controller("Welcome to EAST");
        loader.setController(c);
        Scene scene = new Scene(loader.load());
        fx.setScene(scene); // fx is a JFXPanel which is used to integrate FX in Swing

The above code is working fine, now I want to access the the default values of textFields of the register.fxml in the constructor of Controller Class but It gives and error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException.

Note: I have assigned some default values to the textFields that is why I want to access them.

following is My Controller class

Controller.java

public class Controller {

    @FXML
    private TextField username;
    @FXML
    private PasswordField pass;
    @FXML
    private TextField ip;
    @FXML
    private TextField sPort;
    @FXML
    private TextField fPort;

    public Controller(String str) {
        System.out.println(str);
        System.out.println(ip.getText()); // this line gives the NullPointerException Error
    }

    @FXML
    private void login() {

    }

    @FXML
    private void register(){

    }

    @FXML
    private void cancel(){
        System.exit(0);
    }
}

Any suggestions will be greatly appreciated . Thanks :)

1
2
11/14/2014 6:30:21 AM

You don't. Before the controls can be injected by the FXMLLoader the controller instance must be created. You use a initialize method instead of the constructor in your controller.

Let your controller implement https://docs.oracle.com/javafx/2/api/javafx/fxml/Initializable.html .

Or implement

class MyController {

    @FXML
    public void initialize(){
        //Will be called by FXMLLoader
    }

}
4
11/14/2014 7:24:32 AM

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