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
JFormattedTextField with MaskFormatter
提问by Jeff Storey
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
?
我有一个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);
}
}
Unless I'm misunderstanding the question.
除非我误解了这个问题。
回答by trashgod
Alternatively, consider anInputVerifier
, as suggested in InputVerificationDemo
and 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();