现在有这样一个需求我已经创建了一个页面使用borderpane布局然后我再top区域放置了一个menubar并未menubar添加了menu和menuitem现在我想在切换menuitem时切换在center中展示的页面但是我不想再menuitem的回调函数中新建元素然后添加到center区域我希望我可以提前写好几个页面然后当我点击menuitem时可以展示我想要的那个页面我该如何实现
您可以使用JavaFX的Scene和FXML来实现这个需求。
首先,您需要创建不同的FXML文件来描述您想要展示的页面。然后,您可以在程序启动时将这些FXML文件加载并创建对应的Scene对象。当用户点击菜单项时,您可以根据菜单项的ID获取对应的Scene,并将其设置为BorderPane的Center。这样,就可以展示您想要的页面了。
以下是一个简单的示例代码:
public class Main extends Application {
private BorderPane root;
private Map<String, Scene> scenes = new HashMap<>();
@Override
public void start(Stage primaryStage) throws Exception{
// Load FXML files and create corresponding scenes
scenes.put("home", new Scene(FXMLLoader.load(getClass().getResource("home.fxml"))));
scenes.put("about", new Scene(FXMLLoader.load(getClass().getResource("about.fxml"))));
scenes.put("contact", new Scene(FXMLLoader.load(getClass().getResource("contact.fxml"))));
// Create root BorderPane and set initial scene
root = new BorderPane();
root.setTop(createMenuBar());
root.setCenter(scenes.get("home").getRoot());
// Create and show primary stage
primaryStage.setTitle("My App");
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
}
private MenuBar createMenuBar() {
// Create menu items and add them to menu
MenuItem homeMenuItem = new MenuItem("Home");
homeMenuItem.setOnAction(event -> setScene("home"));
MenuItem aboutMenuItem = new MenuItem("About");
aboutMenuItem.setOnAction(event -> setScene("about"));
MenuItem contactMenuItem = new MenuItem("Contact");
contactMenuItem.setOnAction(event -> setScene("contact"));
Menu menu = new Menu("Menu");
menu.getItems().addAll(homeMenuItem, aboutMenuItem, contactMenuItem);
// Create and return menu bar
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
return menuBar;
}
private void setScene(String sceneId) {
// Get scene from map and set it as root of center pane
root.setCenter(scenes.get(sceneId).getRoot());
}
public static void main(String[] args) {
launch(args);
}
}
在这个示例中,我们首先在程序启动时加载了三个FXML文件并创建了对应的Scene对象,并将它们存储在一个Map中。然后,我们创建了一个MenuBar,并添加了三个MenuItem,分别对应着我们想要展示的三个页面。当用户点击某个MenuItem时,我们调用setScene方法,根据传入的sceneId获取对应的Scene,并将其设置为BorderPane的Center。这样,就可以展示我们想要的页面了。
注意,我们在创建MenuBar时,将每个MenuItem的回调函数都设置为调用setScene方法。这样,每个MenuItem都可以切换到对应的页面。而且,由于我们提前创建了所有的页面,并将它们存储在Map中,所以不需要在回调函数中再次创建页面。
原文地址: https://www.cveoy.top/t/topic/b72S 著作权归作者所有。请勿转载和采集!