Вопрос

i know how to put an initial value for JTextFiled, but how to set the property of the value to be fixed?

This is the normal way for the value

JTextFiled is = new JTextFiled("00:00:00");

Sure, the output will be a text field with value 00:00:00, but the user can delete that. How can I stop that from happening? The value of the field is 00:00:00, if the user tries to delete the value Java will stop him if he tried to edit the value. The only way is by using numbers from the keyboard.

Это было полезно?

Решение

Option 1 - Use a JFormattedTextField with a SimpleDateFormat:

JFormattedTextField textField = new JFormattedTextField(new SimpleDateFormat("HH:mm:ss:SSS"));
textField.setText("00:00:00:000");
  • You can replace the format string according to your needs by looking at the SimpleDateFormat API.
  • This pattern works as long as the movie is not longer than 24 hours.
  • This way the user can delete the string, but once he leaves the text field the string will return to what it was before. Only strings of the specified format will actually be accepted as the value.

Option 2 - Use a JFormattedTextField with a MaskFormatter:

MaskFormatter mask = null;
try {
    mask = new MaskFormatter("##:##:##:###");
} catch (ParseException e) {
    e.printStackTrace();
}
mask.setValidCharacters("0123456789");
mask.setPlaceholderCharacter('0');
JFormattedTextField textField2 = new JFormattedTextField(mask);
textField2.setText("00:00:00:000");
  • You can replace the format string according to your needs by looking at the MaskFormatter API.
  • This pattern works as long as the movie is not longer than 99 hours, but minutes and seconds count can exceed 59 (e.g. you can have 01:76:98:123 read: 1 hour 76 minutes 98 seconds 123 milliseconds).
  • This way the user can only type digits (specified by "0123456789") and deleting any of the numbers will replace them with 0 (specified by '0').

Другие советы

this is how to disable the backspace function

textField.getInputMap().put(KeyStroke.getKeyStroke("BACK_SPACE"), "none");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top