2012-06-26 18 views
3

我想要一个用户输入时间,就像12:00一样,但我需要弄清楚一些事情,我很失败。有没有办法把一个冒号放在jtextfield中,所以不能被删除?

  1. 我可以将文本限制为5个字符吗?
  2. 我可以在代码中嵌入一个冒号,以便它不能被用户删除吗?
  3. 最后,我可以采取代码并验证它仅仅是个数字(忽略当然,结肠)
+4

使用[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)。 –

回答

7

答案是使用JFormattedTextFieldMaskFormatter

例如:

String mask = "##:##"; 
MaskFormatter timeFormatter = new MaskFormatter(mask); 
JFormattedTextField formattedField = new JFormattedTextField(timeFormatter); 

Java编译器将要求你赶上或创建MaskFormatter之外时,抛出一个ParseException,所以一定要做到这一点。

+0

我不能得到这个工作。掩码格式化程序和文本字段在引发异常之前允许使用10个字符,并且它仍然不允许我使用: public void textformat()MaskFormatter mask = null; try {mask} = new MaskFormatter(“##:##”); mask.setPlaceholderCharacter(':'); (ParseException e){ } catch } JFormattedTextField sunb = new JFormattedTextField(mask); jFormattedTextField1 = sunb; } – rdemolish

2

或者只是沟通您的文本字段并选择两个JSpinner实例(由含有冒号(或两个JTextField实例)的JLabel分开)。

不完全确定这个解决方案对用户会更直观,但我认为是这样。

0

对老问题的回答较晚;使用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 { } 

}); 
相关问题