2010-11-23 95 views
11

我有一個JFormattedTextField,我用它來限制日期和時間的條目。我想用MaskFormatter來顯示佔位符字符。當文本字段已經使用SimpleDateFormat時,有沒有辦法在JFormattedTextField的頂部使用MaskFormatter帶MaskFormatter的JFormattedTextField

感謝, 傑夫

回答

27
public class MaskFormatterTest { 
    private static final DateFormat df = new SimpleDateFormat("yyyy/mm/dd"); 


    public static void main(String[] args) { 
     JFrame frame = new JFrame(""); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel = new JPanel(); 

     JFormattedTextField tf = new JFormattedTextField(df); 
     tf.setColumns(20); 
     panel.add(tf); 
     try { 
      MaskFormatter dateMask = new MaskFormatter("####/##/##"); 
      dateMask.install(tf); 
     } catch (ParseException ex) { 
      Logger.getLogger(MaskFormatterTest.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     frame.add(panel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

alt text

除非我誤解的問題。

2

另外,考慮一個InputVerifier,如InputVerificationDemo建議,這更復雜example

+0

謝謝。我認爲@ I82Much的答案更簡單,但這在其他情況下也會有用,而不是編寫自定義焦點偵聽器。 – 2010-11-23 03:34:57

+0

我同意!我的例子有點複雜,但適用於多種允許的日期格式。順便說一句,我的+1到@ I82Much。 – trashgod 2010-11-23 04:16:11

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – Cyclonecode 2014-05-23 00:12:12

-2
JFormattedTextField tft3 = 
    new JFormattedTextField(new SimpleDateFormat("yyyy-MM-dd")); 
    tft3.setValue(new Date()); 

    Date date = (Date) tft3.getValue();