Reputation: 371
I tried to load an FXML and set the controller with Java code (not with the FXML tag). I have different fields in the FXML. I tried to load (for example textfields, buttons...).
Here is the example:
Tab tab = new Tab();
tab.setText("TesetTabAdd");
tabpane.getTabs().add(tab);
FXMLLoader loader = new FXMLLoader(getClass().getResource("tab.fxml"));
TabController tabCont = new TabController();
tabCont.setName("Sandro");
loader.setController(tabCont);
try {
tab.setContent((Node)loader.load(getClass().getResource("tab.fxml")));
} catch (IOException ex) {
System.out.println(ex);
}
As you can see I create a new Tab, set the text for it, add it to the tabpane, load the fxml and then I create a new controller and set it as controller for the FXML. After this, I tried to set a value in the fxml before initialize so that I can use it in my controller to update a textfield or button.
Here is my controller, I tried to set:
public class TabController implements Initializable {
@FXML private TextField name;
private final StringProperty nameProp = new SimpleStringProperty();
public String getNameProp() {
return nameProp.get();
}
public void setNameProp(String value) {
nameProp.set(value);
}
public StringProperty namePropProperty() {
return nameProp;
}
public void setName(String name){
nameProp.setValue(name);
}
public String getName(){
return nameProp.get();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
name.textProperty().bind(nameProp);
}
}
I tried it with binding, but it doesn't work.
I edit my createTab() method a littel bit. Here i set the controller and then use the setName method. But i the textfield dont display anything. The System.out.println(tabCont.getName());
method prints out "Sandro"!!!
public void createTab(){
try{
Tab tab = new Tab();
tab.setText("TesetTabAdd");
tabpane.getTabs().add(tab);
FXMLLoader loader = new FXMLLoader();
TabController tabCont = new TabController();
loader.setController(tabCont);
tabCont.setName("Sandro");
tab.setContent((Node)loader.load(getClass().getResource("tab.fxml")));
System.out.println(tabCont.getName());
} catch (IOException ex) {
System.out.println(ex);
}
}
Upvotes: 0
Views: 5387
Reputation: 49215
1) the FXML file is not loaded until the load()
method is invoked.
(as per your comment "... load the fxml and then I create a new controller ...
"). So just initiating the FXMLLoader will not load the given fxml file.
2) You are invoking a wrong load method. You should use the load method of instantiated FXMLLoader. But you used static load method of the FXMLLoader class. This static version will ignore the controller class set through setController()
. Try:
FXMLLoader loader = new FXMLLoader(getClass().getResource("tab.fxml"));
TabController tabCont = new TabController();
tabCont.setName("Sandro");
loader.setController(tabCont);
try {
tab.setContent((Node) loader.load());
} catch (IOException ex) {
System.out.println(ex);
}
Upvotes: 3