I'm writing a program in Java and I'm using JavaFX for the GUI, using the MVC way.
The structure of the view I'm talking about is as follow:
The reason for this structure is because I want to keep my code clean & clear.
Inside the TopPane I want only a menuBar.
I've added this as follow:
public class TopPane extends Pane {
private MenuBar menuBar;
public TopPane() {
initNodes();
layoutNodes();
}
private void initNodes() {
Menu[] menus = new Menu[3];
menus[0] = new Menu("File");
menus[1] = new Menu("Options");
menus[2] = new Menu("Help");
MenuItem[] menuItemsFile = new MenuItem[4];
menuItemsFile[0] = new MenuItem("New game");
menuItemsFile[1] = new MenuItem("Save game");
menuItemsFile[2] = new MenuItem("Load game");
menuItemsFile[3] = new MenuItem("Exit");
menus[0].getItems().addAll(menuItemsFile);
MenuItem options = new MenuItem("Options");
menus[1].getItems().add(options);
MenuItem help = new MenuItem("Help");
menus[2].getItems().add(help);
menuBar = new MenuBar();
menuBar.getMenus().addAll(menus);
}
private void layoutNodes() {
menuBar.setMinWidth(Double.MAX_VALUE);
menuBar.useSystemMenuBarProperty().set(true);
getChildren().add(menuBar);
}
public MenuBar getMenuBar() {
return menuBar;
}
}
In gameview I do the following:
public class GameView extends BorderPane {
private TopPane topPane;
private LeftPane leftPane;
private PlayerView playerView; //centerpane
private RightPane rightPane;
public GameView() {
initNodes();
layoutNodes();
}
private void initNodes() {
topPane = new TopPane();
leftPane = new LeftPane();
playerView = new PlayerView();
rightPane = new RightPane();
}
private void layoutNodes() {
this.setStyle("-fx-background-color: #2a2a2a");
this.setTop(topPane);
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
double screenHeight = screenBounds.getHeight();
int topMargin = 25;
if (screenHeight >= 1050) {
topMargin = 150;
}
System.out.println(screenHeight);
setMargin(leftPane, new Insets(topMargin, 0, 0, 50));
this.setLeft(leftPane);
setMargin(playerView, new Insets(0, 0, 0, 25));
this.setCenter(playerView);
this.setRight(rightPane);
}
}
It shows the menubar succesfully but the problem is that when I click one of the menus, the menuItems just flickers and dissapear immediatly. I think this is because I extend topPane with Pane. But without it couldn't work obviously, and if I extend from menuBar (and delete the variable Menubar), my rightPane & PlayerView won't be added to my GameView for some mysterious dark reason I couldn't figure out (yet) :)
Anybody able to help me? Thanks in advance!
Thanks to DVarga :
This works perfectly!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.