bio photo

Nifty 0.0.5 adds support for a Drop Down Control. Here we show how to actually use it.

XML</strong>

First of all you need to add the standard Nifty controls to your xml. To keep things easy for the moment we use the default Nifty styles too.

</pre>
So adding a Drop Down Control works like adding any other control:

Basically you address the control you want to add, in this case it's "dropDownControl". And you need to give your control an id too, so that you can reference it later ("dropDown1").


Java</strong>

Back in Java you want to populate your new Drop Down Control with data.

For this you need the Drop Down Control Class. With Nifty 0.0.5 there is a new method on the Nifty Screen class that makes selecting Controls even easier:

public class Screen {
...
public < T extends Controller > T findControl(
final String elementName,
final Class < T > requestedControlClass) ...</pre>
Looks complicated but it is really easy to use. To get the Drop Down Control instance from a Screen we simply use the following line:
DropDownControl dropDown1 = screen.findControl("dropDown1", DropDownControl.class);</pre>
And now that we have the instance we can use it to add items to the Drop Down Control:
dropDown1.addItem("Nifty GUI");
dropDown1.addItem("Slick2d");
dropDown1.addItem("Lwjgl");</pre>
Set the Selected Item</strong>

To select a value from the Drop Down Control we can use the setSelectedItem() or setSelectedItemIdx() methods:

public void setSelectedItemIdx(final int idx)
public void setSelectedItem(final String text)</pre>
The first allows you to select the Item with its index and the second can be used to select the text items directly.

So we use:

dropDown1.setSelectedItemIdx(2);
or
dropDown1.setSelectedItem("Lwjgl");</pre>
to select the last Item.

Get the Selected Item</strong>

Getting the selected Item works - you guessed it - the same. You can use one of the following methods:

public int getSelectedItemIdx()
public String getSelectedItem()</pre>
So you can get the index of the selected item or the String directly:
assertEquals(2, dropDown1.getSelectedItemIdx());
or
assertEquals("Lwjgl", dropDown1.getSelectedItem());</pre>
That's it! Nifty!

Have Fun! :D