This is a simple class that implements the TextFieldFilter interface to enforce correct floating point entry into scene2d text fields. It actually took a few hours trying to catch all the incorrect cases.
- Code: Select all
package com.suds.tools;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
/**
* Org.: DefeatThePurpose Entertainment
* User: Suds (Scott Drew) <suds@defeatthepurpose.net>
* Date: 19/09/2014
* Time: 5:56 PM
*/
public class FloatTextFilter implements TextField.TextFieldFilter {
@Override
public boolean acceptChar(TextField textField, char c) {
if(Character.isDigit(c) && !textField.getText().contains("-")) return true;
else if(Character.isDigit(c) && textField.getCursorPosition() > 0) return true;
else if(c == '-' && textField.getText().length() == 0) return true;
else if(c == '.' && !textField.getText().contains(".") && !textField.getText().contains("-")) return true;
else if(c == '.' && !textField.getText().contains(".") && textField.getText().contains("-")) return textField.getCursorPosition() > 0;
else if(c == '-' && !textField.getText().contains("-")) return textField.getCursorPosition() == 0;
return false;
}
}
here is a paste link, in case the code blocks on the forum suck for copying from: http://pastie.org/private/frcthqxyb5lasxnspeahqa
