在JavaFX中创建垂直菜单栏

Tom*_*omJ 2 javafx menu menubar menuitem javafx-2

由于我与计算机的交互,我只看到了水平方向的菜单栏.这种菜单栏的菜单将向下弹出.在JavaFX中,使用水平菜单栏创建这样的菜单很容易.

是否可以在JavaFX中创建垂直菜单栏?此外,我希望菜单项向左或向右弹出,而不是向下弹出.

我可以实现我的愿望这样的菜单吗?有人请帮忙.

Ulu*_*Biy 5

你可以利用MenuButton这个:

@Override
public void start(Stage primaryStage) {
    MenuButton m = new MenuButton("Eats");
    m.setPrefWidth(100);
    m.setPopupSide(Side.RIGHT);
    m.getItems().addAll(new MenuItem("Burger"), new MenuItem("Hot Dog"));

    MenuButton m2 = new MenuButton("Drinks");
    m2.setPrefWidth(100);
    m2.setPopupSide(Side.RIGHT);
    m2.getItems().addAll(new MenuItem("Juice"), new MenuItem("Milk"));

    VBox root = new VBox();
    root.getChildren().addAll(m, m2);

    Scene scene = new Scene(root, 300, 250);
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
    primaryStage.setScene(scene);
    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

其中的style.css

.menu-button {
    -fx-skin: "com.sun.javafx.scene.control.skin.MenuButtonSkin";
    -fx-background-color: red, green, green, lightgreen;
    -fx-background-insets: 0 0 -1 0, 0, 1, 2;
    -fx-background-radius: 0;
    -fx-padding: 0.0em; /* 0 */
    -fx-text-fill: -fx-text-base-color;
}

/* TODO workaround for RT-19062 */
.menu-button .label { -fx-text-fill: -fx-text-base-color; }

.menu-button:focused {
    -fx-color: beige;
    -fx-background-color: -fx-focus-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
    -fx-background-insets: -1.4, 0, 1, 2;
    -fx-background-radius: 0;
}

.menu-button:hover {
    -fx-color: darkgreen;
}

.menu-button:armed {
    -fx-color: greenyellow;
}
Run Code Online (Sandbox Code Playgroud)

这些选择器部分被从caspian.css中获取并覆盖.根据需要更改颜色首选项,您还可以通过css删除按钮的箭头.

这种方法的缺点是难以制作嵌套的菜单项.