bio photo

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

XML</strong></p>

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:</p>

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></p>

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:</p>
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:</p>
dropDown1.addItem("Nifty GUI");
dropDown1.addItem("Slick2d");
dropDown1.addItem("Lwjgl");</pre>
Set the Selected Item</strong></p>

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.</p>

So we use:

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

Get the Selected Item</strong></p>

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:</p>
assertEquals(2, dropDown1.getSelectedItemIdx());
or
assertEquals("Lwjgl", dropDown1.getSelectedItem());</pre>
That's it! Nifty!</p>

Have Fun! :D