如何使用DocumentFilter设置可以在Jformattedtextfield中输入的最大值和最小值? [英] How to set a Maximum and Minimum value that can be entered in a Jformattedtextfield , using DocumentFilter?

查看:120
本文介绍了如何使用DocumentFilter设置可以在Jformattedtextfield中输入的最大值和最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java编程的新手.我有一个文档过滤器,该过滤器只允许使用."表示数值和小数.在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); 
      }
    }

现在在我使用的主要代码中调用该过滤器:

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

是否有任何简单的方法可以设置可以在JFormattedTextField中输入的最大值和最小值?

解决方案

JTextField可与自定义这里

I am newbie to Java programming. I have a document filter that only allow numeric values and decimals with "." in a JFormattedTextField. Now I want to implement a method within that filter, to only allow a maximum and minimum value , like I want whatever the value of number entered, it must be between [0-1], otherwise it should not accept whatever is typed.

Now I don't want to use JSpinner, because from 0 to 1 there is millions of Decimals eg: 0.0001, 0.0012 ...

This is my documentFilter code:

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); 
      }
    }

Now to call for that Filter in my main code I use:

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

Is there any simple way to set Maximum and Minimum value that can be entered in a JFormattedTextField?

解决方案

A JTextField can be used with a custom DocumentFilter that checks values are numeric and within the specified range. Below is a sample DocumentFilter that accomplishes just that:

public class RestrictedNumberDocumentFilter extends DocumentFilter{

    private double min;
    private double max;

    public RestrictedNumberDocumentFilter(double min, double max){
        if ( max < min ){
            double temp = max;
            max = min;
            min = temp;
        }
        this.min = min;
        this.max = max;
    }

    @Override
    public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) throws BadLocationException {
        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        if ( test(sb.toString()) ){
            fb.insertString(off, str, attr);
        }else{
            //warn
        }

    } 
    @Override
    public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)throws BadLocationException{
        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(off, off+len, str);
        if ( test(sb.toString()) ){
            fb.replace(off, len, str, attr); 
        }else{
            //warn
        }

    }
    /**
     * Sanitized the input
     * @param val
     * @return
     */
    private boolean test(String val){
        try{
            double d = Double.parseDouble(val);
            if ( d >= min && d <= max ){
                return true;
            }
            return false;
        }catch(NumberFormatException e){
            return false;
        }
    }
}

To use this class, set the DocumentFilter for the Document of the JTextField

JTextField field = new JTextField();
AbstractDocument doc =  (AbstractDocument )field.getDocument();
doc.setDocumentFilter(new RestrictedNumberDocumentFilter (min, max));

You might need to customize this class further for whatever input you anticipate.

You can do a similar thing with a JFormattedTextField, but it may have its own issues with using a custom DocumentFilter as described here

这篇关于如何使用DocumentFilter设置可以在Jformattedtextfield中输入的最大值和最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆