Getting TextField value programatically

I have created a GUI that had 2 textfields and a button. Basicallyt its username, password and login button.

I’m having trouble getting the strings of the text currently written on the textfields.



Is there a way to do it similar to:



Element username = nifty.getCurrentScreen().findElementByName(“username_txt”);

String user=username.getRenderer(TextRenderer.class).getWrappedText();



Or do I have to register a ontextchanged event and get the text from there?

[java]

@Override

public void bind(Nifty nifty, Screen screen) {

/* Retrieve instances of the gui elements. */

m_tfUsername = screen.findNiftyControl("controlID", TextField.class); //username textfield

m_tfPassword = screen.findNiftyControl("controlID", TextField.class); //password textfield

}



//later



… = m_tfUsername.getText();

… = m_tfPassword.getText();

[/java]

I used the eventsubscriber to get it:



@NiftyEventSubscriber(id = “password_txt”)

public void onPasswordChanged(final String id, final TextFieldChangedEvent event)

{

password = event.getText();

System.out.print(“text:”+password );

}



Can’t help thinking there has to be a better way to do it but 5 lines of code isn’t that bad.

@atomr said:
I used the eventsubscriber to get it:

@NiftyEventSubscriber(id = "password_txt")
public void onPasswordChanged(final String id, final TextFieldChangedEvent event)
{
password = event.getText();
System.out.print("text:"+password );
}

Can't help thinking there has to be a better way to do it but 5 lines of code isn't that bad.


Wouldn't that be triggered at every keystroke? You sure you want that?
1 Like

psalm “control api” on page 98 in the Nifty bible should be of help here. it even has an example for getting the text of a Textfield …



edit



[java]TextField textField = screen.findNiftyControl(“input”, TextField.class);

String text = textField.getText();[/java]



still I suggest reading psalm “control api” on page 98 in the Nifty bible :wink:

2 Likes

Thank you guys. Those are indeed much better sugestions :slight_smile: