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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With