使用JavaFX将数据传递到已经打开的窗口中

问题描述 投票:0回答:1

我是JavaFX的新手。没有FXML,这很容易做到,但是FXML控制器让我很沮丧。

我想做的事情:设置一个带有按钮的主窗口。单击按钮会启动一个弹出窗口,用户可以在其中完成操作并单击按钮。单击此按钮将关闭弹出窗口,然后主窗口会确认用户的操作已完成?

到目前为止,我已经设置了.fxml和控制器。单击第一个窗口的按钮将启动第二个窗口。第二个窗口的按钮单击接受用户的输入并将其存储,但是我无法弄清楚如何将该数据发送回主窗口。

如果尚未打开用于接收数据的窗口,那么我已经能够使用以下代码(这是打开第二个窗口的原因:]

    @FXML
    private void popBtnClick(ActionEvent event) throws IOException {
        Stage popupSave = new Stage();
        popupSave.initModality(Modality.NONE);
        popupSave.initOwner(ComWins.stage);

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("PopUp.fxml"));
        Parent root = loader.load();

        PopUpController controller = loader.getController();
        controller.dataToPopUp(7);

        Scene scene = new Scene(root);
        popupSave.setScene(scene);
        popupSave.show();
}

    public void dataToPopUp(int x){
        input_tf.setText(Integer.toString(x));
}

上面的代码将“ 7”传递到第二个窗口的文本字段中。如何将信息从第二个窗口传递到第一个永远不会关闭的窗口?

谢谢你。这感觉很简单,但是我无法弄清楚。

javafx controller fxml message-passing fxmlloader
1个回答
0
投票

我是这样做的。首先创建一个界面

public interface DataSender {
 void send(String data);
}

然后将该接口实现到您的主窗口控制器

public class FXMLDocumentController implements Initializable,DataSender {

@FXML
private Label label;

@FXML
private void handleButtonAction(ActionEvent event) {

    try {
        Stage popupSave = new Stage();
        popupSave.initModality(Modality.NONE);
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("PopUp.fxml"));
        Parent root = loader.load();

        PopUpController controller = loader.getController();
        controller.setX(7);
        //this is the line use to get data from popup
        controller.setSendDataSender(this);

        Scene scene = new Scene(root);
        popupSave.setScene(scene);
        popupSave.show();
    } catch (IOException ex) {
        Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
    }
}



@Override
public void send(String data) {
    label.setText(data);
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}
}

然后重写已实现的接口方法,在该方法内部您可以更改主窗口UI数据,也可以更改标签文本。

然后在数据类型为DataSender的pupup控制器中创建create变量(创建的接口befor)并创建用于设置该接口的方法

public class PopUpController implements Initializable {

private int x;

//this is the variable
private DataSender dataSender;


@FXML
private Button btnOk;
@FXML
private TextField txtText;

@Override
public void initialize(URL url, ResourceBundle rb) {
    btnOk.setOnAction(e->{
        //When Click this button will call Main Window send method
        dataSender.send(txtText.getText());
    });
}

public void setX(int x){
    this.x=x;
}

//this is the method to set variable value from Main Window
public void setSendDataSender(DataSender ds){
    this.dataSender=ds;
}

}

然后单击弹出窗口按钮,然后使用数据调用send方法,然后将更改主窗口标签文本。此解决方案对我有用。希望对您也有用。

© www.soinside.com 2019 - 2024. All rights reserved.