首页 > 解决方案 > JavaFx 将 Window-Control-Buttons 添加到菜单栏(类似 IntelliJ)

问题描述

由于 IntelliJ 版本 2019.2 Jetbrains 从 IDE 中移除了标题栏,并将窗口的最小化、最大化和关闭按钮放入菜单栏中。到目前为止,我还没有找到如何使用 javafx 来做到这一点。有没有办法实例化一个“WindowControlButtons”类,所以我可以轻松地将它们添加到菜单栏,还是我必须自己添加一个按钮组并为每个平台设置按钮样式?

示例它在 Windows 上的外观:

示例图像

标签: javafxwindowcontrolsstylesmenubar

解决方案


正如@mr mcwolf您可以尝试以下解决方案所建议的那样。

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class JavaFXApplication1 extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button closeButton = new Button();
        closeButton.setText("X");
        closeButton.setOnAction((ActionEvent event) -> {
            javafx.application.Platform.exit();
        });
        Button hideButton = new Button();
        hideButton.setText("-");
        hideButton.setOnAction((ActionEvent event) -> {
            primaryStage.setIconified(true);
        });
        Menu menu = new Menu("Menu");
        MenuItem menuItem1 = new MenuItem("item 1");
        MenuItem menuItem2 = new MenuItem("item 2");
        menu.getItems().add(menuItem1);
        menu.getItems().add(menuItem2);
        MenuBar menuBar = new MenuBar();
        menuBar.getMenus().add(menu);
        HBox hBox = new HBox(menuBar, hideButton, closeButton);
        HBox.setHgrow(menuBar, Priority.ALWAYS);
        HBox.setHgrow(hideButton, Priority.NEVER);
        HBox.setHgrow(closeButton, Priority.NEVER);
        BorderPane root = new BorderPane();
        root.setTop(hBox);
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.initStyle(StageStyle.UNDECORATED);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Windows 上的输出如下所示。

在此处输入图像描述


推荐阅读