问题
I want a user to input time, so like 12:00, but I need to figure out a few things and I am wicked lost.
- Can I limit the text to 5 characters and how?
- Can I have a colon embedded in the code so that it cant be deleted by the user?
- Finally, can I take that code and verify that it is only the digits (ignoring the colon of course)
回答1:
The answer is to use a JFormattedTextField and a MaskFormatter.
For example:
String mask = "##:##";
MaskFormatter timeFormatter = new MaskFormatter(mask);
JFormattedTextField formattedField = new JFormattedTextField(timeFormatter);
The Java compiler will require that you catch or throw a ParseException when creating your MaskFormatter, and so be sure to do this.
回答2:
Or just ditch your textfield and opt for two JSpinner
instances separated by a JLabel
containing the colon (or two JTextField
instances).
Not completely sure that this solution will be more intuitive to the user, but I think so.
回答3:
a late answer to an old question; making use of DocumentFilter
may achieve that three req's.
a non-production quality code may be like this
String TIME_PATTERN = "^\\d\\d:\\d\\d\\s[AP]M$";
final JTextField tf = new JTextField("00:00 AM", 8);
((AbstractDocument)tf.getDocument()).setDocumentFilter(new DocumentFilter() {
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength());
text = text.substring(0, offs) + str + text.substring(offs + length);
if(text.matches(TIME_PATTERN)) {
super.replace(fb, offs, length, str, a);
return;
}
text = fb.getDocument().getText(0, fb.getDocument().getLength());
if(offs == 2 || offs == 5)
tf.setCaretPosition(++offs);
if(length == 0 && (offs == 0 ||offs == 1 ||offs == 3 ||offs == 4 ||offs == 6))
length = 1;
text = text.substring(0, offs) + str + text.substring(offs + length);
if(!text.matches(TIME_PATTERN))
return;
super.replace(fb, offs, length, str, a);
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { }
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { }
});
来源:https://stackoverflow.com/questions/11215449/is-there-a-way-to-put-a-colon-in-a-jtextfield-so-it-cant-be-removed