How to create a scrollable context menu in JavaFX?

I have a situation where the context menu could potentially contain hundreds of menu items. By default, the scroll buttons at the top / bottom of the popup window will be displayed in the context menu, but it occupies the full height of the screen. I tried to set the values ​​of maxHeight and prefHeight, but this did not affect.

Ideally, I would like to show the scroll bar instead of the scroll buttons at the top and bottom (i.e. put it in the scroll bar).

Here is the code snippet that I currently have:

ContextMenu menu = new ContextMenu(); menu.setMaxHeight(500); menu.setPrefHeight(500); for(TabFX<T> tab : overflowTabs) { MenuItem item = new MenuItem(tab.getTabName()); if (tab.getGraphic() != null) item.setGraphic(tab.getGraphic()); item.setOnAction(e -> { select(tab); layoutTabs(); }); menu.getItems().add(item); } Point2D p = overflowBtn.localToScreen(0, overflowBtn.getHeight()); menu.show(overflowBtn, p.getX(), p.getY()); 

Is there a workaround for this?

+4
source share
1 answer

I had the same problem and solved it using the javafx.stage.Popup class with ScrollPane , which contains a VBox and contains menu items.

 Popup popup = new Popup(); VBox vBox = new VBox(); for (int i = 0; i < 4; i++) { Button item = new Button("item " + i); item.setOnAction(...); vBox.getChildren().add(item); } ScrollPane scrollPane = new ScrollPane(vBox); scrollPane.setMaxHeight(500);//Adjust max height of the popup here scrollPane.setMaxWidth(200);//Adjust max width of the popup here popup.getContent().add(scrollPane); popup.show(rootWindow); 

Note. Since you cannot put MenuItem in a VBox , I used Button in the example because it has a setOnAction(...) method. But you can use whatever you like :)

+1
source

All Articles