我有一个父控制器,其中包含一个按钮.当我点击按钮时,它打开新窗口并将一些数据显示在表格中.我用于打开窗口的代码是
Stage stage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("../layout/SearchCustomer.fxml")); Parent parent = (Parent) fxmlLoader.load(); Scene scene = new Scene(parent); stage.initModality(Modality.APPLICATION_MODAL); stage.initOwner(parent.getScene().getWindow()); stage.setScene(scene); stage.resizableProperty().setValue(false); stage.showAndWait();
它正确打开窗口.现在我需要的是,当我双击子窗口的表行时,它应该在父控制器文本框中设置一些值.我们如何将这个值从子控制器传递给父控制器?
在子控制器中公开属性,并从"父"控制器中观察它.你的问题中没有足够的信息来给出准确的答案,但它看起来像是:
public class ChildController { @FXML private TableViewcustomerTable ; private final ReadOnlyObjectWrapper currentCustomer = new ReadOnlyObjectWrapper<>(); public ReadOnlyObjectProperty currentCustomerProperty() { return currentCustomer.getReadOnlyProperty() ; } public Customer getCurrentCustomer() { return currentCustomer.get(); } public void initialize() { // set up double click on table: customerTable.setRowFactory(tv -> { TableRow row = new TableRow<>(); row.setOnMouseClicked(e -> { if (row.getClickCount() == 2 && ! row.isEmpty()) { currentCustomer.set(row.getItem()); } } }); } }
然后你就是这样做的:
Stage stage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("../layout/SearchCustomer.fxml")); Parent parent = (Parent) fxmlLoader.load(); ChildController childController = fxmlLoader.getController(); childController.currentCustomerProperty().addListener((obs, oldCustomer, newCustomer) -> { // do whatever you need with newCustomer.... }); Scene scene = new Scene(parent); stage.initModality(Modality.APPLICATION_MODAL); stage.initOwner(parent.getScene().getWindow()); stage.setScene(scene); stage.resizableProperty().setValue(false); stage.showAndWait();
另一种方法是Consumer
在子控制器中使用a 作为回调:
public class ChildController { @FXML private TableViewcustomerTable ; private Consumer customerSelectCallback ; public void setCustomerSelectCallback(Consumer callback) { this.customerSelectCallback = callback ; } public void initialize() { // set up double click on table: customerTable.setRowFactory(tv -> { TableRow row = new TableRow<>(); row.setOnMouseClicked(e -> { if (row.getClickCount() == 2 && ! row.isEmpty()) { if (customerSelectCallback != null) { customerSelectCallback.accept(row.getItem()); } } } }); } }
在这个版本中你做到了
Stage stage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("../layout/SearchCustomer.fxml")); Parent parent = (Parent) fxmlLoader.load(); ChildController childController = fxmlLoader.getController(); childController.setCustomerSelectCallback(customer -> { // do whatever you need with customer.... }); Scene scene = new Scene(parent); stage.initModality(Modality.APPLICATION_MODAL); stage.initOwner(parent.getScene().getWindow()); stage.setScene(scene); stage.resizableProperty().setValue(false); stage.showAndWait();