抛砖引玉:import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
import java.text.*;
import dtool.*;
public class FormattedSample {
public static void main (String args[]) throws ParseException {
JFrame f = new JFrame("JFormattedTextField Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
// Four-digit year, followed by month name and day of month,
// each separated by two dashes (--)
DateFormat format =
new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter df = new DateFormatter(format);
JFormattedTextField ftfTime = new
JFormattedTextField(df);
ftfTime.setValue(new Date());
content.add(ftfTime);
// US Social Security number
MaskFormatter mfNumber =
new MaskFormatter("###-##-####");
mfNumber.setPlaceholderCharacter('_');
JFormattedTextField ftfNumber = new
JFormattedTextField(mfNumber);
content.add(ftfNumber);
// US telephone number
MaskFormatter mfTel =
new MaskFormatter("(###) ###-####");
JFormattedTextField ftfTel = new
JFormattedTextField(mfTel);
content.add(ftfTel); //US color's formate
MaskFormatter mfColor =
new MaskFormatter("AAAAAA");
JFormattedTextField ftfColor = new
JFormattedTextField(mfColor);
content.add(ftfColor);
f.setSize(400, 100);
f.show();
}
}
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
import java.text.*;
import dtool.*;
public class FormattedSample {
public static void main (String args[]) throws ParseException {
JFrame f = new JFrame("JFormattedTextField Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
// Four-digit year, followed by month name and day of month,
// each separated by two dashes (--)
DateFormat format =
new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter df = new DateFormatter(format);
JFormattedTextField ftfTime = new
JFormattedTextField(df);
ftfTime.setValue(new Date());
content.add(ftfTime);
// US Social Security number
MaskFormatter mfNumber =
new MaskFormatter("###-##-####");
mfNumber.setPlaceholderCharacter('_');
JFormattedTextField ftfNumber = new
JFormattedTextField(mfNumber);
content.add(ftfNumber);
// US telephone number
MaskFormatter mfTel =
new MaskFormatter("(###) ###-####");
JFormattedTextField ftfTel = new
JFormattedTextField(mfTel);
content.add(ftfTel); //US color's formate
MaskFormatter mfColor =
new MaskFormatter("AAAAAA");
JFormattedTextField ftfColor = new
JFormattedTextField(mfColor);
content.add(ftfColor);
f.setSize(400, 100);
f.show();
}
}
1 这段代码正好就存在这个问题,在输入年的时候,你没办法限定输入的是4位年份,而数字限定格式####是可以的,四个#就只能输入4个数字!
2 关于月和日的输入,java采取的策略是进位,譬如输入2004--八月--34,它自动变成2004--九月--03,这当然没错,但理想的方法是当输入3再输入4是输不进去的(应该能自动判断输入格式是否正确,如不正确就拒绝输入),当然这用监听器也能实现,但我希望是不是有更直接便捷的方法。