【问题标题】:JFormattedTextField with MaskFormatter带有 MaskFormatter 的 JFormattedTextField
【发布时间】:2011-05-14 05:28:39
【问题描述】:

我有一个JFormattedTextField,我用它来限制日期和时间的输入。我想使用MaskFormatter 来显示占位符字符。当文本字段已经使用SimpleDateFormat 时,有没有办法在JFormattedTextField 之上使用MaskFormatter

谢谢, 杰夫

【问题讨论】:

    标签: java swing datetime textfield


    【解决方案1】:

    或者,考虑InputVerifier,如InputVerificationDemo 中所建议的那样,以及更详细的example

    【讨论】:

    • 谢谢。我认为@I82Much 的答案更简单,但这在其他情况下也很有用,而不是编写自定义焦点侦听器。
    • 我同意!我的示例有点复杂,但对于多种允许的日期格式来说很方便。顺便说一下,+1 给@I82Much。
    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    • @KristerAndersson:同意;我引用了更可靠的来源,包括供应商赞助的教程和 SO 本身的答案。
    【解决方案2】:
    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);
        }
    }
    

    除非我误解了这个问题。

    【讨论】:

      【解决方案3】:
      JFormattedTextField tft3 = 
          new JFormattedTextField(new SimpleDateFormat("yyyy-MM-dd"));
          tft3.setValue(new Date());
      
          Date date = (Date) tft3.getValue();
      

      【讨论】:

      • 这不使用屏蔽输入字段
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      相关资源
      最近更新 更多