publicstaticvoidmain(Stringargs[])throwsParseException{JFramef=newJFrame("JFormattedTextField Sample");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);...Containercontent=f.getContentPane();content.setLayout(newBoxLayout(content,BoxLayout.PAGE_AXIS));DateFormatformat=newSimpleDateFormat("dd/MM/yy");DateFormatterdf=newDateFormatter(format);JFormattedTextFieldftf1=newJFormattedTextField(df);ftf1.setValue(newDate());content.add(ftf1);MaskFormattermf1=newMaskFormatter("###-##-####");mf1.setPlaceholderCharacter('_');JFormattedTextFieldftf2=newJFormattedTextField(mf1);content.add(ftf2);...// US telephone numberMaskFormattermf2=newMaskFormatter("(###) ###-####");JFormattedTextFieldftf3=newJFormattedTextField(mf2);content.add(ftf3);f.setSize(300,100);f.show();}
e este aqui:
packageorg.kodejava.example.swing;importjavax.swing.*;importjavax.swing.text.MaskFormatter;importjavax.swing.text.DateFormatter;importjava.awt.*;importjava.text.DateFormat;importjava.text.SimpleDateFormat;importjava.text.ParseException;importjava.util.Date;publicclassFormattedTextFieldExampleextendsJFrame{publicFormattedTextFieldExample(){initComponents();}privatevoidinitComponents(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(newDimension(200,200));getContentPane().setLayout(newFlowLayout(FlowLayout.LEFT));MaskFormattermask=null;try{//// Create a MaskFormatter for accepting phone number, the # symbol accept// only a number. We can also set the empty value with a place holder// character.//mask=newMaskFormatter("(###) ###-####");mask.setPlaceholderCharacter('_');}catch(ParseExceptione){e.printStackTrace();}//// Create a formatted text field that accept a valid phone number.//JFormattedTextFieldphoneField=newJFormattedTextField(mask);phoneField.setPreferredSize(newDimension(100,20));//// Here we create a formatted text field that accept a date value. We// create an instance of SimpleDateFormat and use it to create a// DateFormatter instance which will be passed to the JFormattedTextField.//DateFormatformat=newSimpleDateFormat("dd-MMMM-yyyy");DateFormatterdf=newDateFormatter(format);JFormattedTextFielddateField=newJFormattedTextField(df);dateField.setPreferredSize(newDimension(100,20));dateField.setValue(newDate());getContentPane().add(phoneField);getContentPane().add(dateField);}publicstaticvoidmain(String[]args){SwingUtilities.invokeLater(newRunnable(){publicvoidrun(){newFormattedTextFieldExample().setVisible(true);}});}}