JavaFX 下拉按钮

JavaFX drop down button

如何在 JavaFX 中创建 "Drop down button"?

到目前为止,我一直在使用 ChoiceBox,现在我必须将图像分配给 ChoiceBox

ChoiceBox.setGraphic() // is not available as like Buttons

所以我打算将其更改为下拉按钮。这样我就可以给它设置一个图标了。

我正在使用 SceneBuilder 设计 UI。

在搜索如何使用 JavaFX 创建下拉按钮方面没有帮助。

如果您不必像 ChoiceBox 那样存储选择,您可以使用例如 MenuButton 控件。

MenuButton is a button which, when clicked or pressed, will show a ContextMenu.

A MenuButton 有你提到的 graphicProperty 因为它的基础 class 是 Labeled.

简单示例

final Image image = new Image(getClass().getResource("cross_red.png").toExternalForm(), 20, 20, true, true);
MenuButton menuButton = new MenuButton("Don't touch this");
menuButton.setGraphic(new ImageView(image));
menuButton.getItems().addAll(new MenuItem("Really"), new MenuItem("Do not"));

这将生成如下按钮:

注意:如果您需要按钮也像一个真正的按钮,您可以从MenuButton切换到SplitMenuButton。唯一的区别是控制字段分为按钮部分和下拉部分(因此您也可以为 header 分配一个动作):

The SplitMenuButton, like the MenuButton is closely associated with the concept of selecting a MenuItem from a menu. Unlike MenuButton, the SplitMenuButton is broken into two pieces, the "action" area and the "menu open" area.

If the user clicks in the action area, the SplitMenuButton will act similarly to a Button, firing whatever is associated with the ButtonBase.onAction property.