ContextMenus are designed to open upon right-clicking a widget. This version of the context menu should be integrated during the creation of the widget class itself.
Here is the ideal way to utilize a ContextMenu within a widget:
public class MyWidget extends Widget {
// Other fields....
private ContextMenu menu;
private boolean bool = false;
public MyWidget(String modId) {
super(DATA, modId);
createMenu();
}
public void createMenu(){
menu = new ContextMenu(getX(), getY());
menu.addOption(new BooleanOption("boolean", () -> this.bool, value -> this.bool = value));
// Add more options
}
@Override
public void renderWidget(DrawContext context, int mouseX, int mouseY) {
menu.render(drawContext, getX(), getY(), (int) Math.ceil(getHeight()));
// Render your widget here
if (bool){
// Do something with the boolean modified by the user.
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (button == GLFW.GLFW_MOUSE_BUTTON_RIGHT && widgetBox.isMouseOver(mouseX, mouseY)) {
menu.toggleDisplay();
}
menu.mouseClicked(mouseX, mouseY, button);
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
public void mouseReleased(double mouseX, double mouseY, int button) {
menu.mouseReleased(mouseX, mouseY, button);
super.mouseReleased(mouseX, mouseY, button);
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, int snapSize) {
menu.mouseDragged(mouseX, mouseY, button);
return super.mouseDragged(mouseX, mouseY, button, snapSize);
}
@Override
public void onClose() {
super.onClose();
menu.close();
}
}
While this setup is ideal, it offers high customization options such as altering its position in the render call, display duration, the triggering action for its display, closing mechanisms, and more.