Justplayit94
Justplayit94

Reputation: 423

JavaFX Adding a button to top-right of window

I am designing a GUI in JavaFX and I've added to it a MenuBar with different MenuItems. I also want it to be undecorated from the Windows default Close and Minimize buttons, so I've called the methodsinitStyle(StageStyle.UNDECORATED) on the Stage object. Now I'm trying to put a close button on the top right of the window so that my user can close the now resulted window, but I can't do so with the BorderPanes setTop() method, because it falls under the MenuBar item.
Is there a way to float or add the button on top of the MenuBar ?
Or at least have the X button in another menu bar that will be positioned before the current menu bar.

This is how it looks right now with the code I have:
enter image description here
This is the code I ahve so far in the start() method:

public void start(Stage primaryStage) throws Exception {
    window = primaryStage;
    window.setTitle("Menu Example");


    MenuBar file = new MenuBar();
    file.setId("file");

    Menu fileMenu = new Menu("File");
    fileMenu.getItems().addAll(
            new MenuItem("New File..."),
            new MenuItem("Open file..."),
            new MenuItem("Save file"));
    fileMenu.setId("#fileMenu");



    Menu editMenu = new Menu("Edit");
    editMenu.getItems().addAll(
            new MenuItem("Undo"),
            new MenuItem("Redo"),
            new MenuItem("Cut"),
            new MenuItem("Copy"),
            new MenuItem("Paste")
    );

    Button closeButton = new Button("X");
    closeButton.setOnAction(event -> {
        Platform.exit();
    });
//        closeButton.setAlignment(Pos.TOP_RIGHT);

    file.getMenus().addAll(
            fileMenu,
            editMenu

    );

    layout = new BorderPane();
    layout.setTop(file);
    layout.setRight(closeButton);

    Scene scene = new Scene(layout, 300, 300);
    scene.getStylesheets().add("Viper.css");
    window.setScene(scene);
//        window.setMaximized(true);
    window.initStyle(StageStyle.UNDECORATED);
    window.show();
}

Upvotes: 2

Views: 5657

Answers (1)

fabian
fabian

Reputation: 82451

Place the Button and the MenuBar next to each other in a HBox and make sure the MenuBar is the only one of those nodes that grows:

HBox hbox = new HBox(file, closeButton);

HBox.setHgrow(file, Priority.ALWAYS);
HBox.setHgrow(closeButton, Priority.NEVER);

layout.setTop(hbox);
//layout.setRight(closeButton);

Upvotes: 7

Related Questions