我正在尝试使用在另一个场景中选择的值填充场景中的 TextField。
因此,有一个场景(我将其称为父场景),其中包含一个 TextField 和一个可打开另一个场景(我将其称为子场景)的按钮。子场景有一个 TableView,我想将其选定值设置为父场景的 TextField。仅当带有 TextField 的场景尚未打开时,我才知道如何执行此操作,在我的情况下,子场景的舞台设置为 showAndWait。所以我想我需要获取父场景的舞台并将其设置为子 Controller 下面的 select() 方法中的舞台字段。
//子 Controller 中的方法,在从 tableview 中选择一行时调用
public void select() throws IOException
{
Class class = (Class)table.getSelectionModel().getSelectedItem();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getClassLoader().getResource("parentStage.fxml"));
Parent parent = loader.load();
Stage stage = // here i need to pass the parent stage I think;
stage.initModality(Modality.APPLICATION_MODAL);
ParentController parentController = loader.getController();
table.setOnMouseClicked(event -> {
if(event.getClickCount()==2){
parentController.setTextField(new TextField(class.getValue()));
stage.setScene(new Scene(parent));// also,
I think, here it should be passed the already opened parent scene
stage.show();
((Node)(event.getSource())).getScene().getWindow().hide();
} });
//这是父场景中打开子场景的按钮的方法
public void add() throws IOException
{
Parent parent = FXMLLoader.load(getClass().getClassLoader().getResource("childStage.fxml"));
stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stageProdusNou.setScene(new Scene(parent));
stageProdusNou.showAndWait();
}
谢谢。
最佳答案
您可以执行此操作,无需重新加载基本布局,方法是:
- 从第二个 Controller 创建对象
- 在第二个 Controller 中创建一个方法,将传递的文本字段初始化为本地文本字段。
- 使用创建的对象和方法将文本字段传递到第二个 Controller 。
- 当第二个 Controller 上发生操作时更新您的文本字段。
这个答案是代码和步骤的总结here 。
关于java - 当两个场景都显示时,我可以在一个场景中设置另一个场景中的 TextField 值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299893/