Reputation: 31
I try to do an application with JavaFX. I have a little question :
Unfortunatly, i can't do this. I would like that '/' and '.' are always write in the TextField. I also would like when the user has wrote the fourth first numbers, the TextField set the cursor behind the '/'. So the user don't take care for '/' and '.'. He has just to type the number of the phone number.
How can i do this ?
Thanks for your help,
Mikis
(Sorry for my English ....)
Upvotes: 2
Views: 2296
Reputation: 31
Finaly, i found what i was searching in this project :
https://github.com/jidesoft/jidefx-oss
But i adapted it to my needs. Do I put the code for the new object "MyMaskTextField" ?
Upvotes: 0
Reputation: 2870
You can addListener()
to TextField propertyText
and control the inputs.In your question you did not put any condition so just you need a useful implementation for that you can use this simple code :
TextField field = new TextField();
field.setPromptText("xxxx/xx.xx.xx");
int maxDigits = 13;
field.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
if (newValue.length() == 4 && oldValue.length() != 5) {
field.setText(newValue + "/");
} else if (newValue.length() == 7 && oldValue.length() != 8 || newValue.length() == 10 && oldValue.length() != 13) {
field.setText(newValue + ".");
}
if (newValue.length() > maxDigits) {
field.setText(oldValue);
}
});
Upvotes: 0
Reputation: 36722
You can use a TextFormatter
to control the text inside a TextField.
PhoneNumber TextField described in the question should do the following:
/
after 4 characters.
after 7 and 10 charactersHere is a sample which does all of the above:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TextFieldFormatter extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
final TextField textField = new TextField();
textField.setTextFormatter(new TextFormatter<String>(change -> {
final int oldLength = change.getControlText().length();
int newLength = change.getControlNewText().length();
// Handle backspace
if (newLength < oldLength) return change;
// Add / after 4 characters
// Add . after 7 and 10 characters
// Do not accept more than 13 characters
switch (newLength) {
case 4 :
change.setText(change.getText() + "/");
newLength++;
break;
case 7: case 10:
change.setText(change.getText() + ".");
newLength++;
break;
case 14:
return null;
}
// Set caret position
change.setCaretPosition(newLength);
change.setAnchor(newLength);
return change;
}));
BorderPane root = new BorderPane();
root.setCenter(textField);
Scene scene = new Scene(root, 200, 200);
stage.setScene(scene);
stage.setTitle("TextField Example");
stage.show();
}
}
Upvotes: 2