JavaFX drop down button

江枫思渺然 提交于 2019-12-22 06:47:14

问题


How can I create a "Drop down button" in JavaFX?

So far i was using a ChoiceBox for the purpose , now that I have to assign an image to the ChoiceBox,

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

So I am planning to change it to a drop down button. So that i can set an icon to it.

Am using SceneBuilder for designing UI.

No help in searching how to create a drop down button using JavaFX.


回答1:


If you do not have to store the selection like in a ChoiceBox you can use for example the MenuButton control.

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

A MenuButton has the graphicProperty mentioned by you as its base class is Labeled.

Simple example

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"));

This will produce a button like:

Note: If you need the button also to act like a real button, you can switch from MenuButton to SplitMenuButton. The only difference is that the control field is splitted into a button part and a drop down part (so you can assign an action also for the 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.



来源:https://stackoverflow.com/questions/39163881/javafx-drop-down-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!