我正在使用下面的代码来传递信息,但我想知道其他方式。在 FXMLDocumentController 的事件处理程序方法 handleSubmitButtonAction 中,我创建另一个加载 MainFXML 文件的窗口。之后,我拿到它的 Controller 并将我的信息发送到主窗口。有更好的方法吗?
public class FXMLDocumentController implements Initializable {
@FXML
private TextField user;
@FXML
public void handleSubmitButtonAction(ActionEvent event) throws IOException {
Alert dialogo = new Alert(Alert.AlertType.INFORMATION, "User: " + user.getText() + " logged in.");
dialogo.showAndWait();
Stage stage2 = (Stage) user.getScene().getWindow();
stage2.close();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MainFXML.fxml"));
Parent root = (Parent) fxmlLoader.load();
MainFXMLController controller = fxmlLoader.<MainFXMLController>getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
controller.setUser(user.getText());
}
最佳答案
尝试给出一个简短的答案。
我所做的是创建 Controller 类的“应用程序模型”。应用程序模型的根当然是Application类的 Controller 。应用程序模型不会泄漏 GUI 元素,而是告诉主程序可关闭、已更改等。
public abstract class Part {
public final ObservableMap<String, ActionHandler> getActionHandlers() {...}
public final ObservableBooleanValue closableProperty() {...}
public final ReadOnlyBooleanProperty disabledProperty() {...}
....
}
public abstract class ViewPart extends Part {
public final StringProperty titleProperty() { ... }
public final ReadOnlyObjectProperty<Image> iconProperty() { ... }
....
}
public abstract class Editor extends Part {
public final ObservableBooleanValue dirtyProperty() { .... }
}
就像在 Eclipse 中一样,这些部分可以有自己的窗口,但它们不一定有,它们也可以嵌入到另一个窗口中。该建模大致基于 Eclipse 的结构。
关于java - 在 JavaFX 中窗口之间传递信息的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750345/