我正在研究我的JavaFx项目,我遇到了很多问题。我希望我的两个控制器能够相互通信。我已经阅读了几乎所有这个问题的解决方案,但我无法找到适合我的解决方案。我是初学程序员,我使用了一些现成的解决方案,我不完全理解,对于我的项目,我现在卡住了。我的工作是如此先进,我不能允许重做它。
这是我的代码:
let jsonData = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedIfSafe)
接口类
public class Main extends Application {
public static final String ROOT = "Root";
public static final String ROOT_FXML = "Root.fxml";
public static final String FIRST_SCREEN = "FirstScreen";
public static final String FIRST_SCREEN_FXML = "FirstScreen.fxml";
public static final String SECOND_SCREEN = "SecondScreen";
public static final String SECOND_SCREEN_FXML = "SecondScreen.fxml";
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
ScreensController mainContainer = new ScreensController();
initRootLayout();
mainContainer.loadScreen(Main.FIRST_SCREEN, Main.FIRST_SCREEN_FXML);
mainContainer.loadScreen(Main.SECOND_SCREEN, Main.SECOND_SCREEN_FXML);
mainContainer.setScreen(Main.FIRST_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
rootLayout.setCenter(root);
}
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/Root.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
屏幕控制器类
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
目前我有两个带有两个不同fxml文件的控制器类。它们看起来像这样:
public class ScreensController extends StackPane {
private HashMap<String, Node> screens = new HashMap<>();
public void addScreen(String name, Node screen) {
screens.put(name, screen);
System.out.println("added screen " + name);
}
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenControler = ((ControlledScreen) myLoader.getController());
myScreenControler.setScreenParent(this);
addScreen(name, loadScreen);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}
public boolean setScreen(final String name) {
if (screens.get(name) != null) {
if (!getChildren().isEmpty()) {
getChildren().remove(0);
// add new screen
getChildren().add(0, screens.get(name));
} else {
getChildren().add(screens.get(name));
}
return true;
} else {
System.out.println("screen hasn't been loaded!\n");
return false;
}
}
public boolean unloadScreen(String name) {
if (screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
第一屏和第二屏之间是否有简单的通讯方式?