我有一个模式类:
public class DialogModal
{
private String fxmlURL;
private int width;
private int height;
public DialogModal( String url, int w, int h )
{
fxmlURL = url;
width = w;
height = h;
}
public void showDialogModal(Button root) throws IOException
{
Stage modalDialog = new Stage();
FXMLLoader loader = new FXMLLoader(getClass().getResource( fxmlURL ));
Parent modalDialogRoot = loader.load();
Scene modalScene = new Scene( modalDialogRoot, width, height );
modalScene.getStylesheets().add(InventoryManager.class.getResource("InventoryManager.css").toExternalForm());
modalDialog.initOwner(root.getScene().getWindow());
modalDialog.setScene(modalScene);
modalDialog.setResizable(false);
modalDialog.showAndWait();
}
}
然后将其打开(从FXML控制器):
@FXML
private void handleModalButton(ActionEvent e) throws IOException
{
DialogModal modal = new DialogModal("Modal.fxml", 400, 450);
modal.showDialogModal((Button)e.getSource());
}
我的问题是,如何将数据从模态(即TextFields)返回到我的handleModalButton
方法?可以为该模式提供不同的FXML文件,因此它返回的数据可能不同。
此外,我如何(或应该)将数据发送到模型(例如,填充TextFields)?
谢谢!
发布于 2018-06-06 09:46:29
您可以让DialogModal.showDialogModal()
返回衍生的模式对话框窗口的控制器。
public <T> T showDialogModal(Button root) throws IOException
{
Stage modalDialog = new Stage();
FXMLLoader loader = new FXMLLoader(getClass().getResource( fxmlURL ));
Parent modalDialogRoot = loader.load();
T controller = loader.getController(); // Retrieve the controller
Scene modalScene = new Scene( modalDialogRoot, width, height );
modalScene.getStylesheets().add(InventoryManager.class.getResource("InventoryManager.css").toExternalForm());
modalDialog.initOwner(root.getScene().getWindow());
modalDialog.setScene(modalScene);
modalDialog.setResizable(false);
// You need Platform.runLater() so that this method doesn't get blocked
Platform.runLater(() -> modalDialog.showAndWait());
return controller; // Return the controller back to caller
}
然后在你的调用方法中:
@FXML
private void handleModalButton(ActionEvent e) throws IOException
{
DialogModal modal = new DialogModal("Modal.fxml", 400, 450);
FooController controller = modal.showDialogModal((Button)e.getSource());
String data1 = controller.getTextField1Data();
// ...
}
您需要确切地知道handleModalButton()
中控制器的类,否则您将得到一个ClassCastException
。当然,您需要在控制器中使用public
getter来公开所需的值。你可以保留像nodes和setters这样的东西private
。
如果您有多个类似于handleModalButton()
的方法,并且对于所有这些方法,您需要获得一组类似的值,那么您可以考虑创建一个接口,您的所有控制器类都可以实现该接口。该接口将包含可从中获取数据的getter方法。然后showDialogModal()
可以返回接口类型,调用方法可以通过接口类型获取控制器对象的引用。
https://stackoverflow.com/questions/50709831
复制相似问题