JavaFX如何在按钮点击事件中编写条件判断实现不同窗口跳转
问题修复方案
错误原因
- 逻辑颠倒:你在点击事件回调内部重新给按钮绑定点击事件,首次点击仅完成绑定不会触发跳转,需要二次点击才会执行跳转逻辑
- 冗余判断:
buttonOnAction触发时,直接通过event.getSource()就能获取到被点击的按钮对象,不需要额外调用isPressed()判断按压状态 - 代码冗余:两个分支的跳转逻辑仅fxml路径不同,无需重复编写大量重复代码
修复后可直接运行的代码
@Override public void buttonOnAction(ActionEvent event){ // 先获取被点击的按钮对应的fxml路径 String fxmlPath = null; Object source = event.getSource(); if (source == btnReaders) { fxmlPath = "readersMenu.fxml"; } else if (source == btnDashboard) { fxmlPath = "librarianMenu.fxml"; } // 统一执行跳转逻辑 if (fxmlPath != null) { try { Parent parent = FXMLLoader.load(getClass().getResource(fxmlPath)); Scene scene = new Scene(parent); Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow(); window.setScene(scene); window.show(); } catch (IOException ex) { ex.printStackTrace(); } } }
更优拓展方案(无需修改点击方法即可新增按钮)
如果后续要新增更多按钮,还可以用userData存对应fxml路径,彻底省略条件判断:
- 界面初始化阶段给每个按钮设置对应fxml路径:
btnReaders.setUserData("readersMenu.fxml"); btnDashboard.setUserData("librarianMenu.fxml"); // 后续新增按钮只要加这一行配置即可
- 点击方法简化为:
@Override public void buttonOnAction(ActionEvent event){ Node sourceBtn = (Node) event.getSource(); String fxmlPath = (String) sourceBtn.getUserData(); if (fxmlPath == null) { return; } try { Parent parent = FXMLLoader.load(getClass().getResource(fxmlPath)); Scene scene = new Scene(parent); Stage window = (Stage) sourceBtn.getScene().getWindow(); window.setScene(scene); window.show(); } catch (IOException ex) { ex.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者it_would_be_better
相关产品推荐
相关产品推荐

