Solved

JTextField Text Validation

Posted on 2001-06-16
3
1,760 Views
Last Modified: 2007-11-27
I am trying to catch the users input for binary validation.

Example:

1) The user will attempt to edit an existing binary string in a JTextField "00001111"
2) If the user enters any text  other than a '1' or a '0',  I want there input to be rejected and the original string remain in the TextField
3) If the user inputs a '1' or a '0'..it will replace the bit as requested

I have a Document listener on thh Field, limiting the amount of binary bits in my string.

I need help on Java Text Validation??

Thanks
0
Comment
Question by:Vernstump
  • 2
3 Comments
 
LVL 92

Accepted Solution

by:
objects earned 100 total points
ID: 6199119
You need to define your own Document model. For your needs it sounds like you simply need to extend PlainDocument, overriding insertString() something like this:

class BinaryDocumentModel extends PlainDocument
{
  public void insertString(int off, String s, AttributeSet a) throws BadLocationException
{
  if (s is only contains 0's & 1's)
    super.insertString(off, s, a);
  else
    Toolkit.getDefaultToolkit.beep();
}
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 6199497
Check out these 2 classes:

package free.util;

import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.AbstractDocument;
import java.awt.Toolkit;


/**
 * A PlainDocument extension which allows to disallow certain changes,
 * by implementing the isChangeAccepted(String, String) method and returning
 * false. A beep is emitted when an attempt to make an unacceptable change is
 * made.
 */

public abstract class StrictPlainDocument extends PlainDocument{



  public StrictPlainDocument(){
    super();
  }



  protected StrictPlainDocument(AbstractDocument.Content c){
    super(c);
  }



  /**
   * Overrides PlainDocument.insertString(int, String, AttributeSet) to
   * check whether the change is accepted before applying the change.
   */

  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException{
    String oldString = getText(0,getLength());
    String newString = new StringBuffer(oldString).insert(offs,str).toString();

    if (isChangeAccepted(oldString,newString))
      super.insertString(offs,str,a);
    else
      Toolkit.getDefaultToolkit().beep();
  }



  /**
   * Returns true if the change from the old text to the new text is acceptable,
   * returns false otherwise.
   */

  public abstract boolean isChangeAccepted(String oldText, String newText);


}





package free.util;


/**
 * A StrictPlainModel which only allows inputting an integer value in a certain
 * range.
 */

public class IntegerStrictPlainDocument extends StrictPlainDocument{

 
  /**
   * The minimum allowed value.
   */

  private final long minValue;



  /**
   * The maximum allowed value.
   */

  private final long maxValue;



  /**
   * The radix of the input.
   */

  private final int radix;




  /**
   * Creates a new IntegerStrictPlainDocument which will only allow inputting
   * integer values in the given radix in the range [minValue..maxValue].
   *
   * @param minValue The minimum allowed value.
   * @param maxValue The maximum allowed value.
   * @param radix The radix of the input.
   */

  public IntegerStrictPlainDocument(long minValue, long maxValue, int radix){
    this.minValue = minValue;
    this.maxValue = maxValue;
    this.radix = radix;
  }




  /**
   * Creates a new IntegerStrictPlainDocument which will only allow inputting
   * integer values in the range [minValue..maxValue].
   *
   * @param minValue The minimum allowed value.
   * @param maxValue The maximum allowed value.
   */

  public IntegerStrictPlainDocument(long minValue, long maxValue){
    this(minValue, maxValue, 10);
  }




  /**
   * Returns true if the new text represents an integer in the correct range when
   * parsed using the appropriate radix, returns false otherwise.
   */

  public boolean isChangeAccepted(String oldText, String newText){
    try{
      long val = Long.parseLong(newText,getRadix());
      if ((val<getMinValue())||(val>getMaxValue()))
        return false;
      else
        return true;
    } catch (NumberFormatException e){
        return false;
      }
  }




  /**
   * Returns the radix used by this IntegerStrictPlainDocument to parse the text.
   */
 
  public int getRadix(){
    return radix;
  }




  /**
   * Returns the minimal allowed value.
   */

  public long getMinValue(){
    return minValue;
  }



  /**
   * Returns the maximal allowed value.
   */

  public long getMaxValue(){
    return maxValue;
  }

 

}


You can use IntegerStrictPlainDocument with new IntegerStrictPlainDocument(Long.MIN_VALUE,Long.MAX_VALUE,2) for what you want.


Sasha Maryanovsky.
0
 
LVL 92

Expert Comment

by:objects
ID: 6209290
Thanks for the points :)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java exception bubble up 2 24
difference between sorce folder and folder in eclipise 3 40
jboss 7.1 start up error 1 58
how to debug htl and js pages 8 53
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question