We are have an error when we try to obtain the first few character of a string
First we tried to remove the last two offending characters
That produced the same error we are seeing when we try to obtain the first few characters
The On Key Typed method is attached to a textfield when MAX character are exceeded a custom alert
is fired. We have looked at many ways to remove or get sub-strings in various SO questions before posting
The string entered will never be the same hence we do not know the specific character to replace
Here is the code and a screen shot of the ERROR notice that the "o" in front of the original text
The string we are entering is "This is a test to see how many yo"
We are trying to obtain only the "This is a test to see how many"
The System.out.println(strNew) is exactly that but when strNew is add to the textfield the "o" shows up
Our question is how to prevent this ?
OR What is the cause of the odd text that is palaced in the textfield?
Here is the Minimal Code to test
public class Atest extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
The Controller
public class testController implements Initializable {
@FXML
TextField txtDesc;
@FXML
private void handleButtonAction(ActionEvent event) {
txtDesc.setText("Thanks");
}
@FXML
private void descLEN(){
txtDesc.setOnKeyTyped(event ->{
int maxCharacters = 10;
if(txtDesc.getText().length() > maxCharacters)
event.consume();
});
}
@Override
public void initialize(URL url, ResourceBundle rb) {
}
We have no idea how to post FXML Code all you need is a TextField
with the id txtDesc and set the OnKeyTyped to descLEN
Because you are consumed with the Custom Alert you may not like our answer
I call this We Hear You Knocking but You Can NOT Come In Your event is consume
OK the answer suggested by Sedrick is great but we have only used 3 Lines of Code
No Custom Alert just 30 Character and a bunch of consuming ha ha
@FXML
private void onType(){
txtDescription.setOnKeyTyped(event ->{
int maxCharacters = 30;
if(txtDescription.getText().length() > maxCharacters)event.consume();
});
All right 7 lines if you count the FXML tab and the declaration and formatting