我有一个模态类:
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 Controller ):
@FXML
private void handleModalButton(ActionEvent e) throws IOException
{
DialogModal modal = new DialogModal("Modal.fxml", 400, 450);
modal.showDialogModal((Button)e.getSource());
}
我的问题是,如何将模式(即 TextFields)中的数据返回到我的 handleModalButton
方法?该模式可以被赋予不同的 FXML 文件,因此它返回的数据可能不同。
此外,我如何(或应该)将数据发送到模式(例如,填充文本字段)?
谢谢!
最佳答案
您可以使 DialogModal.showDialogModal()
返回生成的模式对话框窗口的 Controller 。
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()
中 Controller 的类,否则您将得到ClassCastException
。当然,您需要在 Controller 中具有公开必要值的 public
getter。不过,您可以将节点和 setter 等内容保持为私有(private)
。
如果您有多个类似于 handleModalButton()
的方法,并且对于所有这些方法,您都需要获取一组类似的值,那么您可以考虑创建一个接口(interface),您的所有 Controller 类都可以使用该接口(interface)实现。该接口(interface)将包含您可以从中获取数据的 getter 方法。然后showDialogModal()
可以返回接口(interface)类型,调用方法可以通过接口(interface)类型获取 Controller 对象的引用。
关于JavaFX:从运行时加载的模态获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50709831/