Good and thanks in advance for the help, I need to restrict the values inserted in a JTextField to> 0 and
Good and thanks in advance for the help, I need to restrict the values inserted in a JTextField to> 0 and
A widely used solution is to create your own TextFormatter
, which restricts the entry of user data and prevents the text from reaching the TextField
, so that a higher performance is achieved than launching an event:
@FXML
public TextField mytext;
String regex = "10|[1-9]";
public void initialize(URL location, ResourceBundle resources) {
TextFormatter<String> formatter = new TextFormatter<String>(change -> {
String text = change.getControlNewText();
if (!Pattern.matches(regex, text)) {
change.setText("");
}
return change;
});
mytext.setTextFormatter(formatter);
}
In this case, the data entry is restricted from a regular expression ( 10|[1-9]
) that accepts the number 10 or the numbers between 1 and 9.
This can help you:
private JTextField jTextFieldName =new JTextField();
private int limite = 8;
jTextFieldName.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e){
if (jTextFieldName.getText().length() == limite)
e.consume();
}
});