我正在尝试使用MaskFormatter
with JFormattedTextField
。
在我的课堂上,我有这行代码
JFormattedTextField jtfCNP=new JFormattedTextField(new MaskFormatter(formatCNP));
当我编译时,我得到ParseException
. 我发现解决它的唯一方法是在这样的块内创建MaskFormatter
我的 GUI 面板的构造函数内部的实例try
try { format_cnp=new MaskFormatter("# ###### ######");
jtf_cnp=new JFormattedTextField(format_cnp);
} catch (ParseException pex) {}
jtf_cnp.setColumns(20);
我想要 MaskFormatter 的功能,但没有办法在方法之外实例化它吗?另外,有没有更好的选择MaskFormatter
?
编辑:不起作用的示例代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import javax.swing.text.*;
public class test extends JFrame{
String formatCNP="# ###### ######";
//components
JFormattedTextField jtfCNP=new JFormattedTextField(new MaskFormatter(formatCNP));
public test(){
super("MaskFormatter Test");
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtfCNP.setColumns(20);
add(jtfCNP);
setVisible(true);
}
public static void main(String[] args){
test tf=new test();
}
}