我正在尝试创建一个设置为接受浮点数的文本字段,我正在为此使用正则表达式。我遇到了问题,因为当我输入例如 12345.67 的数字时,当我尝试擦除输入时,我无法擦除1号..为什么?>
import javax.swing.*;
import javax.swing.text.*;
public class DecimalFormatter extends DefaultFormatter {
protected java.util.regex.Matcher matcher;
public DecimalFormatter(java.util.regex.Pattern regex) {
setOverwriteMode(false);
matcher = regex.matcher("");
}
public Object stringToValue(String string) throws java.text.ParseException {
if (string == null) return null;
matcher.reset(string);
if (! matcher.matches())
throw new java.text.ParseException("does not match regex", 0);
return super.stringToValue(string);
}
public static void main(String argv[]) {
JLabel lab1 = new JLabel("Decimal:");
java.util.regex.Pattern Decimal = java.util.regex.Pattern.compile("^[1-9]\\d{0,4}([.]\\d{0,2})?$", java.util.regex.Pattern.CASE_INSENSITIVE);
DecimalFormatter decimalFormatter = new DecimalFormatter(Decimal);
decimalFormatter.setAllowsInvalid(false);
JFormattedTextField ftf1 = new JFormattedTextField(decimalFormatter);
JFrame f = new JFrame("DecimalFormatter Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pan1 = new JPanel(new java.awt.BorderLayout());
pan1.add(lab1, java.awt.BorderLayout.WEST);
pan1.add(ftf1, java.awt.BorderLayout.CENTER);
lab1.setLabelFor(ftf1);
f.getContentPane().add(pan1, java.awt.BorderLayout.SOUTH);
f.setSize(300, 80);
f.setVisible(true);
}
}