I'm trying to get access fields of one controller from another controller, but I'm not having much luck. Basically, I have a Tabpane with two tabs, each of which has its own controller. I have a button on the first tab and a text field on the other. On clicking the button, it should add text to the text field.
I've read some of the ways to fix the problem on here, but none of them worked. Any advice would be greatly appreciated.
Accessing FXML controller class
How to pass object created in FXML Controller1 to Controller2 of inner FXML control
And some google pages
Tab controllers
Utab1ViewController
package com.example.myproject;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import java.net.URL;
import java.util.ResourceBundle;
public class Utab1ViewController implements Initializable {
private Utab2ViewController utab2ViewCtrl;
private Utab2ViewController getUtab2ViewCtrl() throws Exception {
if(utab2ViewCtrl == null) {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("utab2-view.fxml").openStream());
utab2ViewCtrl = (Utab2ViewController) loader.getController();
}
return utab2ViewCtrl;
}
@FXML
private void onClickEvent() {
try {
getUtab2ViewCtrl().updatePage("test1");
System.out.println("test");
}catch(Exception ex) {
ex.printStackTrace();
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
}
Utab2ViewController
package com.example.myproject;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import java.net.URL;
import java.util.ResourceBundle;
public class Utab2ViewController implements Initializable {
@FXML private TextField txtMessage;
public void updatePage(String str) {
txtMessage.setText(str);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
}
FXML files
utab1-view.fxml
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.nhsbsajavafx.Utab1ViewController">
<children>
<Button fx:id="cmdHello" layoutX="248.0" layoutY="188.0" mnemonicParsing="false" text="Hello!" onMouseClicked="#onClickEvent"/>
</children>
</AnchorPane>
utab2-view.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.nhsbsajavafx.Utab2ViewController">
<children>
<TextField fx:id="txtMessage" layoutX="226.0" layoutY="125.0" />
</children>
</AnchorPane>