JavaFX中基于Stage的界面跳转

匿名 (未验证) 提交于 2019-12-02 21:53:52
  • 创建Stage,
/** 工厂 */ public class Factory {     public Stage createStage(String title, int width,int height, String file) throws IOException {         //URL url = getClass().getResource("../../../../" + file);         URL url = Factory.class.getClassLoader().getResource(file);         Parent root = FXMLLoader.load(url);         Stage stage = new Stage();         stage.setTitle(title);         stage.setScene(new Scene(root, width, height));         stage.setResizable(false);         //设置在stage关闭时需要进行的操作         stage.setOnCloseRequest(new EventHandler<WindowEvent>() {             @Override             public void handle(WindowEvent event) {                 //此处当stage关闭时,同时结束程序,避免stage关闭后,程序界面关闭了,但后台线程却依然运行的问题                 System.exit(0);             }         });         //初始化Stage时将该实例添加进StageManager的容器中,方便管理         Context.stageManager.addStage(file.split("\\.")[0], stage);         return stage;     } } /* 注意:     如上述代码所示,获取fxml文件的URL有两种方式,第一种方式只能将fxml文件放在文件夹中才能获取到, 一旦打包为jar包后,如果将fxml文件也打包进了jar文件,那么就无法获取到。     第二种方式,即使打包进jar文件中,也依然能够正常获取到,所以个人推荐第二种方式访问fxml文件。 */
  • 基于Stage的跳转
/** Stage管理类 */ public class StageManager {     private Map<String, Stage> stageMap = new HashMap<>();//存放所有的Stage实例      public void addStage(String name, Stage stage){         stageMap.put(name, stage);     }      public Stage getStage(String name){         return stageMap.get(name);     }      public void closeStage(String name){         stageMap.get(name).close();     }      //实现Stage的跳转,从currentStage跳转到targetStage     public void jump(String currentStageName, String targetStageName){         stageMap.get(currentStageName).close();         stageMap.get(targetStageName).show();     }      public void release(String name){         stageMap.remove(name);     } }
  • 全局上下文
//在全局上下文中,持有StageManager和Factory的实例,使用时从此处获取 public class Context {     public static StageManager stageManager = new StageManager();     public static Factory factory = new Factory(); }
  • 应用
//访问test1.fxml创建Stage,并显示 Stage test1 = Context.factory.createStage("我是标题", 800, 600, "test1.fxml"); test1.show(); //访问test2.fxml创建Stage Context.factory.createStage("我是标题", 800, 600, "test2.fxml"); //从test1跳转到test2 Context.stageManager.jump("test1", "test2");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!