JTexfiled(限制用户输入)

时间:2016-03-10 23:38:52

标签: java

如何限制超过0-4的JTexfiled用户条目(也是双数字)类似于0,0.1,0.232,1,1.2564到4.i已尝试以下代码限制在整数范围内,但我的范围是是整数以及该范围内的十进制数

enter code here
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class RangeSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Range Example");
Container content = frame.getContentPane();
content.setLayout(new GridLayout(3, 2));

content.add(new JLabel("Range: 0-255"));
Document rangeOne = new IntegerRangeDocument(0, 255);
JTextField textFieldOne = new JTextField();

textFieldOne.setDocument(rangeOne);
content.add(textFieldOne);

content.add(new JLabel("Range: -100-100"));
Document rangeTwo = new IntegerRangeDocument(-100, 100);
JTextField textFieldTwo = new JTextField();
textFieldTwo.setDocument(rangeTwo);
content.add(textFieldTwo);

content.add(new JLabel("Range: 1000-2000"));
Document rangeThree = new IntegerRangeDocument(1000, 2000);
JTextField textFieldThree = new JTextField();
textFieldThree.setDocument(rangeThree);
content.add(textFieldThree);

frame.setSize(250, 150);
frame.setVisible(true);
}
}

class IntegerRangeDocument extends PlainDocument {

int minimum, maximum;

int currentValue = 0;

public IntegerRangeDocument(int minimum, int maximum) {
this.minimum = minimum;
this.maximum = maximum;
}

public int getValue() {
return currentValue;
}

public void insertString(int offset, String string, AttributeSet attributes)
throws BadLocationException {

if (string == null) {
return;
} else {
String newValue;
int length = getLength();
if (length == 0) {
newValue = string;
} else {
String currentContent = getText(0, length);
StringBuffer currentBuffer = new StringBuffer(currentContent);
currentBuffer.insert(offset, string);
newValue = currentBuffer.toString();
}
try {
currentValue = checkInput(newValue);
super.insertString(offset, string, attributes);
} catch (Exception exception) {
Toolkit.getDefaultToolkit().beep();
}
}
}

public void remove(int offset, int length) throws BadLocationException {
int currentLength = getLength();
String currentContent = getText(0, currentLength);
String before = currentContent.substring(0, offset);
String after = currentContent.substring(length + offset, currentLength);
String newValue = before + after;
try {
currentValue = checkInput(newValue);
super.remove(offset, length);
} catch (Exception exception) {
Toolkit.getDefaultToolkit().beep();
}
}

public int checkInput(String proposedValue) throws NumberFormatException {
int newValue = 0;
if (proposedValue.length() > 0) {
newValue = Integer.parseInt(proposedValue);
}
if ((minimum <= newValue) && (newValue <= maximum)) {
return newValue;
} else {
throw new NumberFormatException();
}
}
} 

2 个答案:

答案 0 :(得分:1)

从Java 1.4开始,您不再需要使用自定义Document来实现此功能,而是应该使用DocumentFilter

例如......

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JTextField field = new JTextField(10);
                ((AbstractDocument)field.getDocument()).setDocumentFilter(new NumberFilter(0.0, 4.0));

                JFrame frame = new JFrame("Testing");
                frame.setLayout(new GridBagLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class NumberFilter extends DocumentFilter {

        private double min, max;

        // limit is the maximum number of characters allowed.
        public NumberFilter() {
            this(Double.MIN_VALUE, Double.MAX_VALUE);
        }

        public NumberFilter(double min, double max) {
            this.min = min;
            this.max = max;
        }

        @Override
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String str, AttributeSet attrs) throws BadLocationException {
            StringBuilder existing = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
            existing.replace(offset, offset + length, str);
            String text = existing.toString();
            try {
                double value = Double.parseDouble(text);
                if (max >= value && min <= value) {
                    super.replace(fb, offset, length, str, attrs);
                }
            } catch (NumberFormatException exp) {
            }
        }
    }   
}

这是一个非常基本的实现,可能需要更多工作,但应该让你开始朝着正确的方向前进。

有关详细信息,请查看Implementing a Document FilterDocumentFilter Examples

答案 1 :(得分:0)

您需要使用输入验证器并将其与JTextField相关联。

How to validate a JTextField?