带有MaskFormatter的JFormattedTextField
我有一个JFormattedTextField
,用于限制日期和时间的输入。 我想使用MaskFormatter
来显示占位符字符。 当文本字段已经使用SimpleDateFormat
时,有没有办法在JFormattedTextField
之上使用MaskFormatter
?
谢谢,杰夫
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); } }
除非我误解了这个问题。
或者,考虑一个InputVerifier
,如InputVerificationDemo
和更详细的示例所示 。
JFormattedTextField tft3 = new JFormattedTextField(new SimpleDateFormat("yyyy-MM-dd")); tft3.setValue(new Date()); Date date = (Date) tft3.getValue();