使用场景控制器从Main类之外的类(没有FXML)切换JavaFX中的Scene对象?

时间:2018-12-07 20:42:04

标签: java javafx controller javafx-8 project-organization

我正在编写一个JavaFX项目,其中每个场景都是使用其自己的类和对象创建的。

这造成了一个问题,因为我想让这些场景中的每一个都能够切换到程序中的其他场景。

我已经在使用一个全局变量(下面列出的Organizer类)来处理程序中的依赖关系,我宁愿不必使用两个。

除了本地Java和JavaFX,我也不想使用任何FXML或其他任何东西。

如何在Main类之外的Java类中切换场景,而无需创建第二个全局变量,在Main类中创建所有Pane对象或使用FXML?

我的主班:

package mainPackage;

import screens.*;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;

/**
 * Creates Global Variable Organizer
 * Organizer keeps track of various objects
 * 
 * @author LuminousNutria
 */
public class Main extends Application {
   // create initial Pane and Scene
   private Pane mainMenu = new MainMenu().getPane();
   private Scene initialScene = new Scene(mainMenu, 1600, 900);

   // create global Organizer object
   public static Organizer organ = new Organizer();

   @Override
   public void start(Stage stage) {

      organ.setMain(initialScene);

      stage.setScene(initialScene);

      stage.show();
   }

   public static void main(String[] args) {

      launch(args);
   }

//   public getScene = 
}

我的管理器课程:

package mainPackage;

import java.util.HashMap;

import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import screens.*;

/**
 * Keeps track of everything that needs keeping track of.
 * 
 * That includes: Regions Armor Weapons Goods Player gold
 */
public class Organizer {

   // create screen Pane
   private Pane hideout = new Hideout().getPane();

   // create ScreenController object
   private ScreenController sc;

   /**
    * Should only be called once, when the game starts.
    */
   public Organizer() {

      // Create ScreenController and add Panes.
      sc = new ScreenController();
      sc.addScreen("hideout", hideout);
   }

   public void setMain(Scene main) {
      sc.main = main;
   }


   private class ScreenController {
      // holds all the different Panes to be used as Scenes
      private HashMap<String, Pane> screenMap = new HashMap<>();
      // the scene currently displayed
      private Scene main;

      private ScreenController() {}

      // adds a screen to the HashMap
      private void addScreen(String name, Pane pane) {
         screenMap.put(name, pane);
      }

      // removes a screen from the HashMap
      private void removeScreen(String name) {
         screenMap.remove(name);
      }

      // Replaces the root of the scene currently displayed, with another
      private void activate(String name) {
         main.setRoot(screenMap.get(name));
      }

      // Checks to see if a screen is already in the HashMap
      private boolean checkForKey(String key) {
         return screenMap.containsKey(key);
      }
   }

}

0 个答案:

没有答案