简体   繁体   English

如何在JavaFX2上下文菜单中限制MenuItem的宽度

[英]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? 如何限制ContextMenu最大宽度或强制MenuItem内容的文本换行? There is no such property on MenuItem and setting pref/max/min width on the ContextMenu seems not to work. MenuItem上没有这样的属性,并且在ContextMenu上设置pref / max / min宽度似乎不起作用。

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

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. MenuItem有一个默认的内部Labeled组件,用于显示通过MenuItem.setText()设置的文本,看来您很难(如通过CSS ID选择器使用Node.lookup() )到达该Labeled和对其进行操作。 Luckily the other way around is more easier and don't hurt at all I think. 幸运的是,另一种方法更容易实现,而且我认为一点也不受伤。 The other way is to use MenuItem.setGraphic() : 另一种方法是使用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);

You can set the CSS style for the ContextMenu using: 您可以使用以下命令为ContextMenu设置CSS样式:

    ContextMenu menu = new ContextMenu();
    menu.setStyle("-fx-max-width: your-width-value;");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM