Dau Zi
Dau Zi

Reputation: 320

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?

Upvotes: 2

Views: 3268

Answers (2)

mr mcwolf
mr mcwolf

Reputation: 2859

Try this

<BorderPane fx:id="borderPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml">
    <fx:define>
        <ContextMenu fx:id="contextMenu">
            <items>
                <MenuItem text="Menu Item"/>
            </items>
        </ContextMenu>
    </fx:define>
</BorderPane>
public class Controller {

    @FXML
    private ContextMenu contextMenu;

    @FXML
    private BorderPane borderPane;

    @FXML
    private void initialize() {
        borderPane.setOnContextMenuRequested(event -> {
            contextMenu.show(borderPane, event.getScreenX(), event.getScreenY());
        });
    }
}

Upvotes: 5

Sergey Grinev
Sergey Grinev

Reputation: 34508

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>

Upvotes: 5

Related Questions