Nifty GUI: Create a PopUp Menu

Even though you create and populate the popup menu in Java, you still need a “placeholder” in your XML file. The popup element needs to be placed outside of any screen!

<useControls filename="nifty-default-controls.xml"/>
<popup id="niftyPopupMenu" childLayout="absolute-inside"
       controller="ControllerOfYourChoice" width="10%">
  <interact onClick="closePopup()" onSecondaryClick="closePopup()" onTertiaryClick="closePopup()" />
  <control id="#menu" name="niftyMenu" />

A brief explanation of some the attributes above:

  • The popup id is used within your Java code so that nifty knows which popup placeholder to create.

  • The Controller tells Nifty which Java class handles MenuItemActivatedEvent.

  • The on(Secondary/Tertiary)Click tells Nifty to close the popup if the user clicks anywhere except on the menu items (in this example; you have to define the closePopup()-method yourself, in the screen controller)

  • The control id is used by the Java class to define a control type (i.e. Menu)

The Java code within your defined ScreenController implementation:

private Element popup;
public void createMyPopupMenu(){
  popup = nifty.createPopup("niftyPopupMenu");
  Menu myMenu = popup.findNiftyControl("#menu", Menu.class);
  myMenu.setWidth(new SizeValue("100px")); // must be set
  myMenu.addMenuItem("Click me!", "menuItemIcon.png",
    new menuItem("menuItemid", "blah blah")); // menuItem is a custom class
    new MenuItemActivatedEventSubscriber());

public void showMenu() { // the method to trigger the menu
  // If this is a menu that is going to be used many times, then
  // call this in your constructor rather than here
  // call the popup to screen of your choice:
  nifty.showPopup(nifty.getCurrentScreen(), popup.getId(), null);

private class menuItem {
  public String id;
  public String name;
  public menuItem(String id, String name){ id; = name;
  • The createMyPopupMenu() method creates the menu with set width so that you can populate it.

  • The showMenu() method is called by something to trigger the menu (i.e. could be a Key or some other method).

  • Note: if you want to be able to access the popup via your id, use createPopupWithId(id, id) instead.

To handle menu item events (i.e. calling a method when you click on a menu item), you register (subscribe) a EventTopicSubscriber<MenuItemActivatedEvent> class implementation to a nifty screen and element.

  private class MenuItemActivatedEventSubscriber
    implements EventTopicSubscriber<MenuItemActivatedEvent> {

    public void onEvent(final String id, final MenuItemActivatedEvent event) {
    	menuItem item = (menuItem) event.getItem();
       if ("menuItemid".equals( {
		//do something !!!