【发布时间】:2020-01-29 00:36:51
【问题描述】:
我是 JavaFX 的新手。这很容易在没有 FXML 的情况下完成,但是 FXML 控制器让我很难过。
我正在尝试做的事情:设置一个有按钮的主窗口。单击时,该按钮将启动第二个弹出窗口,用户在其中提交一个值。关闭第二个窗口后(目前通过单击弹出窗口上的按钮完成),我希望将用户的输入传递回主控制器 - 已经打开的主窗口。
到目前为止,我有 2 个 .fxml 文件(一个用于主窗口,另一个用于弹出窗口),以及相应的控制器:MainWindowController:
public class MainController implements Initializable {
@FXML
public Label label;
@FXML
private Button button;
@FXML
private void popBtnClick(ActionEvent event) throws IOException {
//creates new pop-up window
Stage popupSave = new Stage();
popupSave.initModality(Modality.APPLICATION_MODAL);
popupSave.initOwner(ComWins.stage);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("PopUp.fxml"));
Parent root = loader.load();
PopUpController controller = loader.getController();
//calls a method in the PopUpController, and uses it to pass data to
//the Popup window.
controller.dataToPopUp(7);
Scene scene = new Scene(root);
popupSave.setScene(scene);
popupSave.showAndWait();
}
I also tried calling this method from the popup window with no success in
changing Main's label.
public void dataPass(String name){
label.setText(name);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
还有 PopUpController:
public class PopUpController implements Initializable {
@FXML
private Button ok_btn;
@FXML
public TextField input_tf;
@FXML
private String input;
@FXML
private void okBtnClick() throws IOException {
input = input_tf.getText();
/*my attempt to pass the variable-- using a loader to get the
controller and then referencing the public label. */
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Main.fxml"));
Parent root = loader.load();
FXMLDocumentController controller = loader.getController();
//this line works, and retrieves the label's text.
String temp = controller.label.getText();
//but this line does not work. Why?
controller.label.setText(input);
//closes this pop-up
Stage stage = (Stage)input_tf.getScene().getWindow();
stage.close();
}
//this method is called in the maincontroller and used to pass data to
//the popup's textfield.
public void dataToPopUp(int x){
input_tf.setText(Integer.toString(x));
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
使用上述方法,Main 将 ('7') 传递到 PopUp 的文本字段中。但是,如果用户在文本字段中输入其他内容,我似乎无法将该数据返回到 Main。这就像有一个设置弹出窗口,然后将用户从设置弹出窗口中的选择传递回主窗口。我只是不知道如何将内容传递回主窗口。
我没有使用 SpringBoot,但感谢您的建议。
提前谢谢你!
【问题讨论】:
-
看看here 的想法是否有帮助。
标签: javafx controller fxml fxmlloader