Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFormattedTextField with MaskFormatter

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

like image 271
Jeff Storey Avatar asked Nov 23 '10 02:11

Jeff Storey


2 Answers

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.

like image 107
I82Much Avatar answered Sep 18 '22 15:09

I82Much


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

like image 41
trashgod Avatar answered Sep 18 '22 15:09

trashgod