JFormattedTextField with MaskFormatter

≡放荡痞女 提交于 2019-12-17 11:45:09

问题


I have a JFormattedTextField that I use to restrict entries of a date and time. I want to use a MaskFormatter though to show the placeholder chars. Is there a way to use a MaskFormatter on top of the JFormattedTextField when the text field is already using a SimpleDateFormat?

Thanks, Jeff


回答1:


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);
    }
}

Unless I'm misunderstanding the question.




回答2:


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




回答3:


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

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


来源:https://stackoverflow.com/questions/4252257/jformattedtextfield-with-maskformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!