我想要一个用户输入时间,就像12:00一样,但我需要弄清楚一些事情,我很失败。有没有办法把一个冒号放在jtextfield中,所以不能被删除?
- 我可以将文本限制为5个字符吗?
- 我可以在代码中嵌入一个冒号,以便它不能被用户删除吗?
- 最后,我可以采取代码并验证它仅仅是个数字(忽略当然,结肠)
我想要一个用户输入时间,就像12:00一样,但我需要弄清楚一些事情,我很失败。有没有办法把一个冒号放在jtextfield中,所以不能被删除?
答案是使用JFormattedTextField和MaskFormatter。
例如:
String mask = "##:##";
MaskFormatter timeFormatter = new MaskFormatter(mask);
JFormattedTextField formattedField = new JFormattedTextField(timeFormatter);
Java编译器将要求你赶上或创建MaskFormatter之外时,抛出一个ParseException,所以一定要做到这一点。
我不能得到这个工作。掩码格式化程序和文本字段在引发异常之前允许使用10个字符,并且它仍然不允许我使用: public void textformat()MaskFormatter mask = null; try {mask} = new MaskFormatter(“##:##”); mask.setPlaceholderCharacter(':'); (ParseException e){ } catch } JFormattedTextField sunb = new JFormattedTextField(mask); jFormattedTextField1 = sunb; } – rdemolish
或者只是沟通您的文本字段并选择两个JSpinner
实例(由含有冒号(或两个JTextField
实例)的JLabel
分开)。
不完全确定这个解决方案对用户会更直观,但我认为是这样。
对老问题的回答较晚;使用DocumentFilter
可能实现那三个req的。
非生产质量的代码可能是这样
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 { }
});
使用[JFormattedTextField上](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField。 html)和[MaskFormatter](http://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html)。 –