Java 带有 MaskFormatter 的 JFormattedTextField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4252257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:02:28  来源:igfitidea点击:

JFormattedTextField with MaskFormatter

javaswingdatetimetextfield

提问by Jeff Storey

I have a JFormattedTextFieldthat I use to restrict entries of a date and time. I want to use a MaskFormatterthough to show the placeholder chars. Is there a way to use a MaskFormatteron top of the JFormattedTextFieldwhen the text field is already using a SimpleDateFormat?

我有一个JFormattedTextField用于限制日期和时间的条目。我想使用一个MaskFormatter虽然来显示占位符字符。当文本字段已经使用 a 时,有没有办法MaskFormatter在顶部JFormattedTextField使用 a SimpleDateFormat

Thanks, Jeff

谢谢,杰夫

采纳答案by I82Much

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

替代文字

Unless I'm misunderstanding the question.

除非我误解了这个问题。

回答by trashgod

Alternatively, consider anInputVerifier, as suggested in InputVerificationDemoand this more elaborate example.

或者,考虑一个InputVerifier,如InputVerificationDemo和这个更详细的例子中所建议的。

回答by Mohamed Saligh

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

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