如何使用DocumentFilter设置可以在Jformattedtextfield中输入的最大值和最小值?

时间:2015-05-01 17:33:43

标签: java swing jformattedtextfield documentfilter

我是Java编程的新手。我有一个文档过滤器,只允许数字值和小数与&#34;。&#34;在JFormattedTextField中。现在我想在该过滤器中实现一个方法,只允许最大值和最小值,就像我想要输入的数值一样,它必须在[0-1]之间,否则它不应该接受输入的任何内容。< / p>

现在我不想使用JSpinner,因为从0到1有数百万个小数,例如:0.0001,0.0012 ......

这是我的documentFilter代码:

package javagui.views;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class SeulementNumerique extends PlainDocument  {
    public static final String FLOAT = "0123456789.";
      protected String acceptedChars = null;
      protected boolean negativeAccepted = false;
      public SeulementNumerique() {
        this(FLOAT);
      }
      public SeulementNumerique(String acceptedchars) {  
        acceptedChars = acceptedchars;
      }

      public void setNegativeAccepted(boolean negativeaccepted) {
        if (acceptedChars.equals(FLOAT)) {
          negativeAccepted = negativeaccepted;
          acceptedChars += "-";
        }
      }

      public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {

        if (str == null)
          return;
        for (int i = 0; i < str.length(); i++) {
          if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)
            return;
        }
        if (acceptedChars.equals(FLOAT) || (acceptedChars.equals(FLOAT + "-") && negativeAccepted)) {
          if (str.indexOf(".") != -1) {
            if (getText(0, getLength()).indexOf(".") != -1) {
              return;
            }
          }
        }
        if (negativeAccepted && str.indexOf("-") != -1) {
          if (str.indexOf("-") != 0 || offset != 0) {
            return;
          }
        }
        super.insertString(offset, str, attr); 
      }
    }

现在在我使用的主代码中调用Filter:

formattedTextField_5 = new JFormattedTextField();
formattedTextField_5.setDocument(new SeulementNumerique());

有没有简单的方法来设置可以在JFormattedTextField中输入的最大值和最小值?

1 个答案:

答案 0 :(得分:0)

您可以将minimummaximum字段添加到SeulementNumerique类,并在super.insertString(offset, str, attr)语句之前添加以下代码:

try {
    final String text = getText(0, getLength());
    final String newText = text.substring(0, offset) + str + text.substring(offset);
    final double newValue = Double.valueOf(newText);
    if (newValue < minimum || newValue > maximum)
        return;
} catch (final NumberFormatException e) {
    return;
}
相关问题