-2

How to Restrict JTexfiled User entries beyond 0-4(double numbers also)something Like 0,0.1,0.232,1,1.2564 up to 4.i have tried The following code restrict in a range of whole number but my range to be whole number as well as decimal numbers in that range

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();
}
}
} 
akathir79
  • 31
  • 4
  • 1
    Don't use a `Document` for this, use a `DocmentFilter` see [Implementing a Document Filter](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) and [DocumentFilter Examples](http://www.jroller.com/dpmihai/entry/documentfilter) for more details – MadProgrammer Mar 10 '16 at 23:48
  • Please format your code properly and only give us the bare minimum complete example which shows off your problem. – Daniel Centore Mar 10 '16 at 23:58

2 Answers2

1

Since Java 1.4, it's no longer necessary for you to use a custom Document to implement this functionality, instead, you should now use a DocumentFilter

For example...

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

This is a very basic implementation which might need more work, but should get you started in the right direction.

Have a look at Implementing a Document Filter and DocumentFilter Examples for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You need to use an input validator and associate it with the JTextField.

How to validate a JTextField?

Community
  • 1
  • 1
querist
  • 614
  • 3
  • 11
  • The `InputVerifier` will provide post-validation. Also, if you're just going to link to someone else's answer, you should either post it as a comment (so the rep goes to them) or vote to close the answer as a duplicate. – MadProgrammer Mar 10 '16 at 23:43
  • If I had one more reputation point I would have posted as a comment. Sorry. I was trying to be helpful by pointing the asker toward the InputVerifier. – querist Mar 11 '16 at 00:15
  • thanks. Once I manage that one last reputation point I'll have 50 and I'll be able to comment. – querist Mar 11 '16 at 00:17
  • Still i coudnt get,it is working for whole numbers(0-4) and not for dot(decimal) – akathir79 Mar 11 '16 at 06:15