2017-07-03 32 views
-2

用户单击一个按钮可打开弹出的第二个场景,该场景允许用户选择一些值,然后关闭选区并将其传递到第一个场景。将参数从具有自己控制器的弹出窗口场景传递到主控制器JavaFX

第一个控制器

Set<String> set; 
public void initialize(URL url, ResourceBundle rb){ 
set = new TreeSet<String>(): 
} 
@FXML 
public Set<String> addValue (MouseEvent e) throws IOException { 
Stage stage = new Stage(); 
root = FXMLoader.load(getClass).getResources(2ndFXML.fxml); 
stage.initModality(Modality.APPLICATION_MODAL); 
stage.iniOwner(clickedButton.getScene().getWindow(); 
stage.showAndWait(): 
return set; 
} 

第二控制器

@FXML 
public void addSelection (MouseEvent e) throws IOException { 
if (event.getSource() == button){ 
    stage = (Stage) button.getScene().getWindow(); 
    set.addAll(listSelection) 
    stage.close 
} 

但值永远不会使它回到第一个控制器。

+0

因为你没有添加任何东西到'Set'!如我错了请纠正我。用户从哪里选择值?它是一个ListView吗? – Yahya

+0

在事件处理程序中返回值绝对没有意义。由于您实际上没有调用该方法(它是由JavaFX事件处理框架调用的),因此您将永远无法处理您返回的值。无论如何,'set'是什么:它在哪里定义,你在哪里填充它?你真的想在第一个控制器中用它做什么? –

+0

更新了这个问题。我将从列表视图中选择的内容添加到集合中,并尝试将其传递给第一个控制器 – Moe

回答

2

由于您使用showAndWait(),所有你需要做的是定义在第二控制器的数据的存取方法:

public class SecondController { 

    private final Set<String> selectedData = new TreeSet<>(); 

    public Set<String> getSelectedData() { 
     return selectedData ; 
    } 

    @FXML 
    private void addSelection (MouseEvent e) { 
     // it almost never makes sense to define an event handler on a button, btw 
     // and it rarely makes sense to test the source of the event 
     if (event.getSource() == button){ 
      stage = (Stage) button.getScene().getWindow(); 
      selectedData.addAll(listSelection) 
      stage.close(); 
     } 
    } 

} 

然后在第一个控制器找回它当窗口已经关闭:

@FXML 
public void addValue(MouseEvent e) throws IOException { 

    Stage stage = new Stage(); 
    FXMLLoader loader = new FXMLLoader(getClass().getResource(2ndFXML.fxml)); 
    Parent root = loader.load(); 
    // I guess you forgot this line???? 
    stage.setScene(new Scene(root)); 
    stage.initModality(Modality.APPLICATION_MODAL); 
    stage.iniOwner(clickedButton.getScene().getWindow(); 
    stage.showAndWait(); 

    SecondController secondController = loader.getController(); 
    Set<String> selectedData = secondController.getSelectedData(); 
    // do whatever you need to do with the data... 

} 
+0

我这样做的方式父根= FXMMLoader.load(getClass().....)但这样做你的方式我得到一个错误无法解析加载?在新的FXMLoader.load(....) – Moe

+0

谢谢詹姆斯,我不知道我可以在关闭舞台后得到控制器。 – Moe

+0

@Moe您可以在加载FXML后的任何时间获取控制器。 –

相关问题