Search code examples
javajavafxfxml

How do we define the context menu in FXML?


While I could define the ContextMenu without the FXML, I do not find a good way to define the context menu in FXML:

In source file:

ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().addAll(someMenuItems);
// This runs perfectly

In FXML:

<ContextMenu fx:id="contextMenu">
</ContextMenu>
// This is incorrect in fxml. The Exception of "Unable to coerce javafx.scene.control.ContextMenu to class javafx.scene.Node" is thrown.

<MenuBar fx:id="menuBar">
    //... Some Menu and items could be defined here
</MenuBar>
// This is correct in fxml

I understand that MenuBar works because it extends javafx.scene.control.Control that is a subclass of javafx.scene.Node but ContextMenu does not.

So is there any way to define properties of ContextMenu similarly in FXML?


Solution

  • Try to define it in the corresponding Node context (no pun intended :) through the contextMenu property:

    <TextField fx:id="tf">
        <contextMenu>
            <ContextMenu fx:id="cmTF">
                <items>
                    <MenuItem text="Add"/>
                    <MenuItem text="Remove"/>
                    <MenuItem text="Enhance"/>
                </items>
            </ContextMenu>
        </contextMenu>
    </TextField>