有人能帮帮我吗..。我尝试了所有的方法(包括这里的帮助),但就是不起作用。我使用带有MaskFormatter的JFormattedTextField将数据输入限制在4(最大)位。
static JFormattedTextField textPayout;
MaskFormatter f;
try {
f = new MaskFormatter("####");
} catch (ParseException e) {
e.printStackTrace();
return; // actual code not written yet.
}
textPayout = new JFormattedTextField(f);问题是它既不限制字符也不限制长度(而且,如果输入非数字,文本本身也会重叠)。我已经尝试了各种各样的蒙版操作。有人能告诉我我哪里做错了吗?
谢谢
发布于 2012-02-19 05:59:57
我刚刚尝试了这段代码,它工作得很好,但有一个小问题:
class A extends JFrame {
public static void main(String args[]) throws ParseException {
A a = new A();
a.setLayout(new GridLayout());
JFormattedTextField textField =
new JFormattedTextField(new MaskFormatter("####"));
a.add(textField);
a.add(new JButton("qwe"));
a.setSize(300,50);
a.setVisible(true);
}
}问题是,最初的文本字段是由4个空格填充的,所以我不得不删除它们。这可能是Gentoo编译的IcedTea 7.2的怪异之处。
除此之外,一切都很好,你能试试我的代码吗?如果它不能工作,那么你的Java版本是什么?
发布于 2012-02-19 05:57:05
最简单的方法是使用Number formatter将Document添加到JFormattedTextField,或者使用另一种方法添加DocumentListener (对于example
https://stackoverflow.com/questions/9344321
复制相似问题