workbench555
workbench555

Reputation: 3

Clear TextField From Another Class

In my main FXML controller class Alpha I have a mask with a text field and a button the clear it:

@FXML
private TextField testTF = new TextField();

@FXML
public void clearText() {
    if (testTF != null)
    testTF.clear();
}

If I enter text in to the text field and hit the clear button, the text is being removed. So far, all good.

I have a second controller class Beta. The corresponding fxml file contains the menu layout (menu bar). If the menu item "new" is clicked, it should also clear my text field in class Alpha.

public class Beta {
    private void newApp() {
        Alpha a = new Alpha();
        a.clear();
    }
}

Nothing happens though. What am I doing wrong here? How can I click a button/menu item in a FXML controller class and have it to clear a text field in another FXML controller class?

Upvotes: 0

Views: 1318

Answers (1)

Forager
Forager

Reputation: 317

You should not instantiate testTF with new TextField();: FXMLLoader will automatically assign testTF the corresponding TextField object because you have a @FXML tag.

You're re-instantiating Alpha in class Beta, which exists separately from the one which was created when your fxml was loaded, resulting in two separate private TextField testTF objects. Either give Beta a reference to the first instance of Alpha, or try this alternative:

    public class Alpha implements Initializable {

        public static TextField tf;

        @FXML
        private TextField testTF;

        @Override
        public void initialize(URL location, ResourceBundle resources) {
            tf = testTF;
        }
    }

    public class Beta {
        private void newApp() {
            if (Alpha.tf != null)
                Alpha.tf.clear();
        }
    }

Upvotes: 1

Related Questions