SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
JFormattedTextField txtUsefullife=new JFormattedTextField(df);
txtUsefullife.setValue(new Date());
JFormattedTextField txtUsefullife=new JFormattedTextField(df);
txtUsefullife.setValue(new Date());
import java.awt.*;
import javax.swing.*;
import java.util.*;
import javax.swing.text.*;
import java.text.*;
public class FormatTest extends JFrame
{
public FormatTest()
{
MaskFormatter formatter=null;
try
{
formatter = new MaskFormatter("####-##-##");
}
catch(Exception err)
{
}
JFormattedTextField txt1=new JFormattedTextField(formatter);
JFormattedTextField txt2=new JFormattedTextField(new Float(100.00)); //txt1.setFormatterFactory(new DefaultFormatterFactory(formatter));
txt1.setText("2003-04-05");
txt1.setInputVerifier(new FormattedTextFieldVerifier()); setSize(400,200);
Container con=getContentPane();
con.setLayout(null); txt1.setSize(200,30);
txt1.setLocation(100,0);
txt2.setSize(200,30);
txt2.setLocation(100,100); con.add(txt1);
con.add(txt2); setVisible(true);
} public static void main(String[] args)
{
new FormatTest();
}
}
class FormattedTextFieldVerifier extends InputVerifier
{
public boolean verify(JComponent input)
{
if (input instanceof JFormattedTextField)
{
JFormattedTextField ftf = (JFormattedTextField)input; String text = ftf.getText();
System.out.println(text.trim());
try
{
SimpleDateFormat fm=new SimpleDateFormat("yyyy-mm-dd"); Date da=fm.parse(text);
if ((fm.format(da)).equals(text))
{
return true;
}
else
{
Toolkit kit=ftf.getToolkit();
kit.beep();
return false;
}
}
catch(Exception ee)
{
Toolkit kit=ftf.getToolkit();
kit.beep();
return false;
}
}
return true;
}
public boolean shouldYieldFocus(JComponent input)
{
return verify(input);
}
}
其实可以用正则表达式来验证