Mariusz Jamro Mariusz Jamro - 2 months ago 16
Java Question

How to limit width of MenuItem in JavaFX2 context menu

How to limit max width of

ContextMenu
or force text wrapping of the MenuItem's content? There is no such property on
MenuItem
and setting pref/max/min width on the
ContextMenu
seems not to work.

ContextMenu contextMenu = new ContextMenu();
contextMenu.setPrefWidth(200.0);
contextMenu.setMinWidth(PopupControl.USE_PREF_SIZE);
contextMenu.setMaxWidth(PopupControl.USE_PREF_SIZE);
contextMenu.getItems().add(new MenuItem("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"));

Answer Source

The MenuItem has a default inner Labeled component for showing the text set through MenuItem.setText(), and it seems you have hard way (like using Node.lookup() by the CSS id selectors) to reach that Labeled and manipulate it. Luckily the other way around is more easier and don't hurt at all I think. The other way is to use MenuItem.setGraphic():

Label lbl = new Label("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua");
lbl.setPrefWidth(50);
lbl.setWrapText(true);

MenuItem menuItem = new MenuItem();
menuItem.setGraphic(lbl);

contextMenu.getItems().add(menuItem);