Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX drop down button

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.

like image 221
user3164187 Avatar asked Aug 26 '16 10:08

user3164187


1 Answers

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:

enter image description here

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.

like image 175
DVarga Avatar answered Oct 01 '22 13:10

DVarga