您的期望有很多问题...
首先,您似乎相信格式化字段可以包含任意数量的字符。这不是真的(虽然您可以获得文本,但该字段仍处于它认为无效的状态)。格式化字段要求必须填写掩码的所有位置。
其次,您应该使用该JFormattedTextField#getValue
方法返回字段的值,而不是getText
第三,返回的文本用掩码的占位符 ( MaskFormatter#getPlaceholder
) 填充,它可能是也可能不是空格,所以String#trim
可能不会有帮助......
如果您希望用户只能输入一个可能由 0-n 个字符组成的数值,那么您真的应该考虑使用DocumentFilter
应用于普通JTextField
public class TestField {
public static void main(String[] args) {
new TestField();
}
public TestField() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class NumericDocumentFilter extends DocumentFilter {
private int maxChars;
public NumericDocumentFilter(int maxChars) {
this.maxChars = maxChars;
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
StringBuilder buffer = new StringBuilder(text);
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (!Character.isDigit(ch)) {
buffer.deleteCharAt(i);
}
}
text = buffer.toString();
if (fb.getDocument().getLength() + text.length() > maxChars) {
int remaining = maxChars - fb.getDocument().getLength();
text = text.substring(0, remaining);
}
if (text.length() > 0) {
super.insertString(fb, offset, text, attr);
}
}
@Override
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
public class TestPane extends JPanel {
private JTextField field;
public TestPane() {
setLayout(new GridBagLayout());
field = new JTextField(4);
((AbstractDocument) field.getDocument()).setDocumentFilter(new NumericDocumentFilter(4));
add(field);
field.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(field.getText());
}
});
}
}
}