How to access JavaFX components in the constructor of Controller Class


I am loading an FXML file the following way

        FXMLLoader loader = new FXMLLoader(getClass().getResource("register.fxml"));
        Controller c = new Controller("Welcome to EAST");
        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

public class Controller {

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

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

    private void login() {


    private void register(){


    private void cancel(){

Any suggestions will be greatly appreciated . Thanks :)

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 .

Or implement

class MyController {

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

11/14/2014 7:24:32 AM

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