eriezelagera

Limiting Fields Characters

Feb 10th, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. // LimitDocument.java
  2.  
  3. package edu.tup.prepaid_canteen.actions;
  4.  
  5. import javax.swing.text.AttributeSet;
  6. import javax.swing.text.BadLocationException;
  7. import javax.swing.text.PlainDocument;
  8.  
  9. /**
  10.  * Limit the document's number of input characters.
  11.  * @author Liezl Alfaro & Erieze Lagera
  12.  */
  13. public class LimitDocument extends PlainDocument {
  14.    
  15.     private int limit;
  16.    
  17.     /**
  18.      * Setup the parameter for number of input characters.
  19.      * @param limit Possible limit of characters for a specified document or field.
  20.      */
  21.     public LimitDocument( int limit ) {
  22.         super();
  23.         setLimit(limit);
  24.     }
  25.    
  26.     /**
  27.      * Get the current value for limit.
  28.      * @return The value of <i> limit </i>.
  29.      */
  30.     public final int getLimit() {
  31.         return limit;
  32.     }
  33.    
  34.     @Override
  35.     public void insertString( int offset, String s, AttributeSet attributeSet ) throws BadLocationException {
  36.         if ( offset < limit ) {
  37.             super.insertString(offset,s,attributeSet);
  38.         }
  39.     }
  40.    
  41.     /**
  42.      * Setting new value for input limit without getting instantiated.
  43.      * @param newValue New value for limit.
  44.      */
  45.     public final void setLimit( int newValue ) {
  46.         this.limit = newValue;
  47.     }
  48.    
  49. }
  50.  
  51.  
  52. // Implementing to any fields, invoking from Constructor or jTextField's customize code.
  53. jTextField.setDocument(new LimitDocument(n)); // Where n is the limit of the characters
Advertisement
Add Comment
Please, Sign In to add comment