I'm new to Javafx
, I have a menuBar
and multiple scenes that I can switch between them using the MenuBar
, all worked fine until I tried to do something when clicking the menu item other than showing the scene.
I'm trying to show some writing in the textfield nom
by using the method reload();
of the scene that I'm trying to show, I call the Enfantcontroller
from my homeController
class where I have the menu items action methods and I call the reload()
to write the text to the textfield in enfantView
method when I click the menu item but nothing happens after I load the controller for that scene. here's my code:
EnfantController class
public class EnfantController implements Initializable {
@FXML
private TextField nom;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void reload() {
this.nom.setText("vndghj");
}
}
homeController class
public class CrechHomeController implements Initializable {
/**
* Initializes the controller class.
*/
@FXML
private BorderPane borderPane;
private AnchorPane enfant;
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
// TODO
enfant = FXMLLoader.load(getClass().getResource(("/Views/Enfant.fxml")));
} catch (IOException ex) {
Logger.getLogger(CrechHomeController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
public void enfantItemAction() throws IOException {
// getting the controller class and execute the reload method
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/Views/Enfant.fxml"));
loader.load();
EnfantController enfantController = loader.getController();
enfantController.reload();
borderPane.setCenter(enfant);
}
}
I know I might be overlooking something here, but I can't figure out what it is, help will be appreciated.
You load the fxml in the initialize
method.
In the enfantItemAction
you load the fxml again and use the controller created, but you show the node created in the initialize
method instead.
You need to use the controller created when the fxml you show was loaded, eg
@FXML
public void enfantItemAction() throws IOException {
// getting the controller class and execute the reload method
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/Views/Enfant.fxml"));
Node node = loader.load();
EnfantController enfantController = loader.getController();
enfantController.reload();
borderPane.setCenter(node);
}
Alternatively you could also store the controller created when loading the fxml file in the initialize
method in a field and not load the fxml again in the enfantItemAction
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.