Reputation: 332
I'm trying to validate a TextField, where I only want to allow numbers on the TextField. My code looks like this:
public void handle(KeyEvent evt) {
String character = evt.getCharacter();
if(!character.equals("1")) {
JOptionPane.showMessageDialog(null,evt.getCharacter());
evt.consume();
}
}
This doesn't consume the event :( Is this a bug? Is there another way to do this?
Upvotes: 2
Views: 15950
Reputation: 844
Starting with JavaFX 8u40, the best way to restrict the input of a text field is to set a TextFormatter on the text field. See this answer for details. No need to add event filters or consume events manually.
Upvotes: 2
Reputation: 3126
try this its worked..
txtMobile.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
String character=event.getCharacter();
if(!valid.checkNumeric(character))
event.consume();
}});
and the function for numeric...
public boolean checkNumeric(String value) {
String number=value.replaceAll("\\s+","");
for(int j = 0 ; j<number.length();j++){
if(!(((int)number.charAt(j)>=47 && (int)number.charAt(j)<=57)))
{
return false;
}
}
return true;
}
Upvotes: 4
Reputation: 3165
I think consuming the key events is the wrong approach to this. An arguably simpler and less invasive way to filter the input is to install a listener on the text property and revert it if needed:
public class Test extends Application {
@Override
public void start(final Stage stage) throws Exception {
final Pattern wholeNumberPattern = Pattern.compile("\\d*");
final TextField tf = new TextField();
tf.textProperty().addListener(new ChangeListener<String>() {
public void changed(final ObservableValue<? extends String> observableValue, final String oldValue,
final String newValue) {
if (!wholeNumberPattern.matcher(newValue).matches())
tf.setText(oldValue);
}
});
stage.setScene(new Scene(tf));
stage.show();
}
public static void main(String[] args) {
System.out.println(com.sun.javafx.runtime.VersionInfo.getRuntimeVersion());
Application.launch(args);
}
}
Upvotes: 2