Java jtexfield(限制用户输入)

Java jtexfield(限制用户输入),java,Java,如何将jtexfield用户条目限制在0-4之外(也可以是双精度数字),例如0,0.1,0.232,1,1.2564,直到4。我尝试了以下代码限制在整数范围内,但我的范围是整数以及该范围内的十进制数 enter code here import java.awt.Container; import java.awt.GridLayout; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JLabel;

如何将jtexfield用户条目限制在0-4之外(也可以是双精度数字),例如0,0.1,0.232,1,1.2564,直到4。我尝试了以下代码限制在整数范围内,但我的范围是整数以及该范围内的十进制数

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();
}
}
} 
在此处输入代码
导入java.awt.Container;
导入java.awt.GridLayout;
导入java.awt.Toolkit;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JTextField;
导入javax.swing.text.AttributeSet;
导入javax.swing.text.BadLocationException;
导入javax.swing.text.Document;
导入javax.swing.text.PlainDocument;
公共类样本{
公共静态void main(字符串参数[]){
JFrame=新JFrame(“范围示例”);
容器内容=frame.getContentPane();
setLayout(新的GridLayout(3,2));
添加(新的JLabel(“范围:0-255”);
Document rangeOne=新的IntegerRangeDocument(0,255);
JTextField textFieldOne=新的JTextField();
textFieldOne.setDocument(rangeOne);
content.add(textFieldOne);
添加(新的JLabel(“范围:-100-100”);
文档范围二=新的IntegerRangeDocument(-100100);
JTextField textFieldTwo=新的JTextField();
textFieldTwo.setDocument(范围二);
content.add(textfieldtoo);
添加(新的JLabel(“范围:1000-2000”);
文件范围三=新的集成文件(10002000);
JTextField textFieldThree=新的JTextField();
textFieldThree.setDocument(范围三);
content.add(textfieldtree);
框架。设置尺寸(250、150);
frame.setVisible(true);
}
}
类IntegerRangeDocument扩展了PlainDocument{
int最小值,最大值;
int currentValue=0;
公共整数事务文档(最小整数,最大整数){
这个最小值=最小值;
最大值=最大值;
}
public int getValue(){
返回当前值;
}
公共void insertString(整数偏移量、字符串字符串、属性集属性)
抛出BadLocationException{
if(字符串==null){
返回;
}否则{
字符串newValue;
int length=getLength();
如果(长度==0){
newValue=string;
}否则{
字符串currentContent=getText(0,长度);
StringBuffer currentBuffer=新的StringBuffer(currentContent);
currentBuffer.insert(偏移量,字符串);
newValue=currentBuffer.toString();
}
试一试{
currentValue=检查输入(newValue);
super.insertString(偏移量、字符串、属性);
}捕获(异常){
getDefaultToolkit().beep();
}
}
}
公共void remove(int offset,int length)引发BadLocationException{
int currentLength=getLength();
字符串currentContent=getText(0,currentLength);
前面的字符串=currentContent.substring(0,偏移量);
后面的字符串=currentContent.substring(长度+偏移量,currentLength);
字符串newValue=before+after;
试一试{
currentValue=检查输入(newValue);
超级。删除(偏移、长度);
}捕获(异常){
getDefaultToolkit().beep();
}
}
public int checkInput(字符串proposedValue)引发NumberFormatException{
int newValue=0;
如果(proposedValue.length()>0){
newValue=Integer.parseInt(proposedValue);
}

如果((最小值),则需要使用输入验证器并将其与JTextField关联


自Java 1.4以来,您不再需要使用自定义的
文档来实现此功能,而是现在应该使用
文档过滤器

例如

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) {
            }
        }
    }   
}
导入java.awt.EventQueue;
导入java.awt.GridBagLayout;
导入javax.swing.JFrame;
导入javax.swing.JTextField;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
导入javax.swing.text.AbstractDocument;
导入javax.swing.text.AttributeSet;
导入javax.swing.text.BadLocationException;
导入javax.swing.text.DocumentFilter;
公开课考试{
公共静态void main(字符串[]args){
新测试();
}
公开考试(){
invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
例如printStackTrace();
}
JTextField=新的JTextField(10);
((AbstractDocument)field.getDocument()).setDocumentFilter(新的NumberFilter(0.0,4.0));
JFrame=新JFrame(“测试”);
frame.setLayout(新的GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
帧。添加(字段);
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
});
}
公共类NumberFilter扩展了DocumentFilter{
私人双最小值,最大值;
//limit是允许的最大字符数。
公共数字过滤器(){
这(Double.MIN\u值,Double.MAX\u值);
}
公用号码过滤器(最小值加倍,最大值加倍){
this.min=min;
this.max=max;
}
@凌驾
public void replace(DocumentFilter.FilterBypass fb,int offset,int length,String str,AttributeSet attrs)引发BadLocationException{
StringBuilder existing=新的StringBuilder(fb.getDocument().getText(0,fb.getDocument().getLength());
现有。替换(偏移,偏移+长度,str);
字符串文本=existing.toString();
试一试{
double value=double.parseDouble(文本);

如果(max>=value&&min,
InputVerifier
将提供后期验证。此外,如果您只是想链接到其他人的答案,您应该将其作为注释发布(这样代表就可以找到他们)或者投票将答案作为副本关闭。如果我还有一个信誉点,我会将其作为评论发布。抱歉。我试图通过将询问者指向InputVerifier来提供帮助。谢谢。一旦我管理好最后一个信誉点