Search code examples
javaslick2dnifty-gui

How do I display Button in Nifty GUI without XML?


I'm trying to make a GUI for my game. I've tried various libraries and I've ended up with Nifty. I haven't found any useful tutorial and therefore I'm learning from code examples.

I want to display a simple Button, but it seems that my code is not working. I've tried setting background color of Panel which has been working. I have no idea why the Button is not displaying.

Here's what I have:

protected void prepareNifty(Nifty nifty) {
    ScreenBuilder sb = new ScreenBuilder("start");
    LayerBuilder lb = new LayerBuilder();
    PanelBuilder pb = new PanelBuilder();

    pb.control(new ButtonBuilder("btn1", "First Button!"){{
        alignCenter();
        valignCenter();
        height("5%");
        width("15%");
        backgroundColor(Color.WHITE);
    }});

    pb.childLayoutCenter();
    lb.childLayoutVertical();
    lb.panel(pb);
    sb.layer(lb);

    nifty.addScreen("start", sb.build(nifty));
}

I should add I'm using Slick2D and my class extends NiftyBasicGame.

How can I display the Button and set it an absolute position?


Solution

  • You'll need to load the controls and the styles too when you want to use the default controls, like the Button control.

    Try something like:

    nifty.loadStyleFile("nifty-default-styles.xml");
    nifty.loadControlFile("nifty-default-controls.xml");
    
    new ScreenBuilder("start") {{
      layer(new LayerBuilder("background") {{
        backgroundColor("#f008");
        childLayoutAbsolute();
        control(new ButtonBuilder("showPopupButton", "SHOW") {{
          x(SizeValue.px(100));
          y(SizeValue.px(100));
          interactOnClick("showPopup()");
        }});
      }});
    }}.build(nifty);
    nifty.gotoScreen("start");
    

    Besides that, it might help to read the nifty-gui-the-manual-1.3.2.pdf