JavaFX菜单栏中的右对齐菜单 [英] Right align menu in menubar in JavaFX

查看:364
本文介绍了JavaFX菜单栏中的右对齐菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java Swing中,可以使用以下命令在菜单栏的右侧放置一个菜单:

In Java Swing it is possible to put a menu on the right side of the menu bar using:

menubar.add(menu1);
menubar.add(Box.createHorizontalGlue());
menubar.add(menu2);

这会将menu1放在左侧,将menu2放在右侧.此功能(显然)在JavaFX中不可用.

This will put menu1 on the left and menu2 on the right. This function is (obviously) not available in JavaFX.

JavaFX中,我已经看到可以使用以下工具栏实现相同的目的:

In JavaFX, I have seen that the same can be achieved for a toolbar using:

final Pane rightSpacer = new Pane();
HBox.setHgrow(
    rightSpacer,
    Priority.SOMETIMES
);

尽管如此,此变通办法不适用于菜单.

Although, this workaround is not usuable for menus.

问题:是否可以为JavaFX中的菜单创建正确的分隔符?

Question: is there a way to create a right spacer for menus in JavaFX?

推荐答案

一种小巧的方法是在HBox中使用两个菜单栏.您可以通过向其添加menu-bar样式类,为分隔符提供与菜单栏相同的样式:

One slightly-hacky way would be to use two menu bars in a HBox. You can give the spacer separating them the same style as a menu bar by adding the menu-bar style class to it:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;

public class MenuAlignment extends Application {

    @Override
    public void start(Stage primaryStage) {
        MenuBar leftBar = new MenuBar();
        leftBar.getMenus().addAll(new Menu("File"), new Menu("Edit"));
        MenuBar rightBar = new MenuBar();
        rightBar.getMenus().addAll(new Menu("Help"));
        Region spacer = new Region();
        spacer.getStyleClass().add("menu-bar");
        HBox.setHgrow(spacer, Priority.SOMETIMES);
        HBox menubars = new HBox(leftBar, spacer, rightBar);

        BorderPane root = new BorderPane();
        root.setTop(menubars);
        Scene scene = new Scene(root, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

此方法的潜在缺点是您不能将其用作

A potential disadvantage of this approach is that you couldn't use this as a system menu bar.

这篇关于JavaFX菜单栏中的右对齐菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆