I am a beginner programer and recently I have learned how to switch between scenes in JavaFX. I would like to add a Border Pane (as a container for those scenes ) with some menu buttons, and set scenes in the center (and still be able to switch between them). What should I do or think of ? Here is my code:
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) {
ScreensController mainContainer = new ScreensController();
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);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Interface class
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
Screens controller class
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;
}
}
}
At the moment I have two controller classes with two diffrend fxml files. They look like this:
public class FirstScreenController implements ControlledScreen {
ScreensController myController;
@FXML
void initialize() {
}
@Override
public void setScreenParent(ScreensController screenPage) {
myController = screenPage;
}
}
Is there a way to fix my code ?
I solved problem. Here is new main class