× The internal search function is temporarily non-functional. The current search engine is no longer viable and we are researching alternatives.
As a stop gap measure, we are using Google's custom search engine service.
If you know of an easy to use, open source, search engine ... please contact support@midrange.com.


  • Subject: RE: How to create your own numeric components ?
  • From: Geert Van Landeghem <gvl@xxxxxxxxxxxxxx>
  • Date: Fri, 21 Jan 2000 09:08:50 +0100

Luther,

I think I found a better way to create numeric components:
by creating a subclass of PlainDocument and overriding
the insertString() method to accept only digits and a separator.
I found an example in JFC Unleashed and it works fine! The big advantage
of working with a subclass of PlainDocument is that it can also be used for
other
text components to accept only numeric input.

When creating a JRNumField that acts like a packed decimal 6,2 field
I now have to use the following code:
  JRNumField txf_myfield=new JRNumField(6,2,'.');
  // the setDocument(new PackedFilterDocument(this)) is executed in the
constructor
  // of JRNumField class
  // add the component to the layout ...



For those interested I added the code of my own PackedFilterDocument class:

import java.awt.Toolkit;

import com.sun.java.swing.*;
import com.sun.java.swing.text.*;

public class PackedFilterDocument extends
com.sun.java.swing.text.PlainDocument {
   public static final String NUMBERS = "0123456789.,";
   public JRNumField jrnumfield;
/**
 * TextFilterDocument constructor comment.
 */
public PackedFilterDocument() {
        super();
}
/**
 * TextFilterDocument constructor comment.
 */
public PackedFilterDocument(JRNumField jrnumfield) {
        super();
        this.jrnumfield=jrnumfield;
}

private JRNumField getJrnumfield() {
        return jrnumfield;
}

public void insertString(int offset, String string,AttributeSet
attributeSet) throws com.sun.java.swing.text.BadLocationException {
        /**
         * A String is being inserted into the Document.
         * Ensure that all characters are in NUMBERS.
         *
         * @param offset Where the new string goes.
         * @param string The String to be inserted after check.
         * @param attributeSet Attributes for the new string.
         **/
           
         // If nothing to insert, do nothing.
          
         if( string == null )
                return;

         
         // Ensure each character in the string is a number.
           
         for( int i = 0; i < string.length(); i++ ) {
         if( !valid(offset + i+ 1, string.charAt(i))) {

         
         // Not a number, don't insert the string.
         // Beep to let the user know something is wrong.
           
             Toolkit.getDefaultToolkit().beep();
             return;
         }
   }

   
   // Let our parent do the real work.
   
   super.insertString( offset, string, attributeSet );
}

private void setJrnumfield(JRNumField newValue) {
        this.jrnumfield = newValue;
}

public boolean valid(int offset, char typedChar) {
  // getLength() returns total number of digits
  // getDecimals() returns the digits after the separator
  // getNotation returns the type of separator (comma or period)
  int length= getJrnumfield().getPositions();

  // is character entered correct?
  if( NUMBERS.indexOf(typedChar) == -1 ) {  
        return false;
  }
  try {
  // calculate the position of the separator
  int pos=getText(0,getLength()).indexOf(getJrnumfield().getNotation());
  // set separator to true if separator has allready been entered
  System.out.println("Position=" + pos + " offset=" + --offset);
  boolean separator=pos > -1;

  // calculate the maximum total length in characters
  // if decimals specified add 1 to total length
  if (getJrnumfield().getDecimals() > 0) {
        length++;
  }
 
  // if length of field is equal to maximum length-1
  // consume the KeyEvent: throw it away!
  if (getLength() >= length){
          System.out.println("String to long, Length()=" + getLength() + "
length=" + length);
          return false;
  }
  
  // test the character being entered
  // is character a digit?
  else if (Character.isDigit(typedChar)) {
          System.out.println("It is a digit!");
          // if no decimals specified ok
          if (getJrnumfield().getDecimals() == 0) { return true; }
          // if decimals specified and seperator has been found
          if (getJrnumfield().getDecimals() > 0 && separator) {
                  // is character entered before or after the separator?
                  // Before
                  if  (offset <= pos) {
                          System.out.println("offset <= pos");
                      if (pos >=
getJrnumfield().getPositions()-getJrnumfield().getDecimals()) return false;
else return true;
                  }
                  // After
                  if  (offset >= pos) {
                          System.out.println("offset >= pos");
                      if (getLength()- pos >=
getJrnumfield().getDecimals()+1) return false; else return true;

                  }       
          }
          else if (getJrnumfield().getDecimals() > 0 && !separator) {
                  // if decimals specified and no seperator has been found

              if (getLength() >
getJrnumfield().getPositions()-getJrnumfield().getDecimals()-1) {
                          return false;
                  }
              else return true;
          }    
  }

  // is character equal to separator?
  else if (typedChar== getJrnumfield().getNotation() &&
getJrnumfield().getDecimals() > 0){
          System.out.println("It is a seperator!");
          // if seperator has allready been used?
          if (separator) {
                  System.out.println("Separator has already been used");
                  return false;
          }
          else {
                  System.out.println("This is the separator!");
                  return true;
          }

  }

  // no valid character entered
  // throw away event
  else {
          System.out.println("No seperator and no digit!");
          return false;
  }
  }
  catch(Exception e) {return false;}
  return false;
}
}

----------------------------------------------------------------------------
----------
Geert Van Landeghem
Reynders Etiketten
gvl@reynderseti.be (Office)
hydra@vt4.net (Home)
03/460.12.56 (Office)
0477/759.533 (GSM)

<<never play leapfrog with a unicorn>>
----------------------------------------------------------------------------
----------




-----Original Message-----
From: Luther Ananda Miller [mailto:luther.miller@HYPERE.COM]
Sent: donderdag 20 januari 2000 14:13
To: JAVA400-L@midrange.com
Subject: Re: How to create your own numeric components ?


I will take a guess as to what is happening, although I am not 100% sure. I
use these events to mark that a field has been changed, and I validate the
field later before hitting the database. However, you can use them the way
you want to also I think.

Put a break point in your code which handles the events insertUpdate(),
changeUpdate() and removeUpdate(), and then step trhough. More than likely
you are changing the text to be valid again, which in turn causes a change
which fires the event, causing an endless loop, in which case it would hang
as you describe. I am not sure if you can just consume the event- I haven't
looked into from that perspective yet, but there must be a way to accomplish
what you want to. (Perhaps storing a flag as to whether or not you are
already handling the event when it is fired again,etc)

Luther

----- Original Message -----
From: Geert Van Landeghem <gvl@reynderseti.be>
To: <JAVA400-L@midrange.com>
Sent: Thursday, 20 January 2000 11:51
Subject: RE: How to create your own numeric components ?


> Luther,
>
> Thanks for the advice...
> Indead, with the DocumentListener I can obtain information of where the
> change occurred using insertUpdate(), changeUpdate() and removeUpdate()
> and the DocumentEvent passed. The DocumentEvent interface contains the
> method getOffset() to obtain the starting position of the change...
> wat I needed.
>
> When validition of the entered character isn't succesfull the following
> error occurs:
> the program is locked and the system console doesn't show me that an error
> occured...
> this can only be resolved by ending the program using the debugger of VAJ.
> I change the contents using setText() of the JTextField in insertUpdate()
>
> Is there something I have forgotten? (I'm new to the "flexibility" of
swing)
> With a KeyEvent you can specify consume(), can the same thing be done with
a
> DocumentEvent?
>
> Thanx for responding
>
> --------------------------------------------------------------------------
--
> ----------
> Geert Van Landeghem
> Reynders Etiketten
> gvl@reynderseti.be (Office)
> hydra@vt4.net (Home)
> 03/460.12.56 (Office)
> 0477/759.533 (GSM)
>
> <<never play leapfrog with a unicorn>>
> --------------------------------------------------------------------------
--
> ----------
>
>
>
>
> -----Original Message-----
> From: Luther Ananda Miller [mailto:luther.miller@HYPERE.COM]
> Sent: woensdag 19 januari 2000 16:43
> To: JAVA400-L@midrange.com
> Subject: Re: How to create your own numeric components ?
>
>
> Add a document listener to the document attached to the JTextField. Then
you
> cn listen for the three events which causes chages to the text field value
> regardless of how they are entered (keypress does not cover them all).
Just
> check the end result of the event for validity.
>
> luther
>
> ----- Original Message -----
> From: Geert Van Landeghem <gvl@reynderseti.be>
> To: Java400-L (E-mail) <java400-l@midrange.com>
> Sent: Wednesday, 19 January 2000 16:08
> Subject: How to create your own numeric components ?
>
>
> > Hi All,
> >
> > I'm trying to create my own numeric textfields: I've created a subclass
of
> > JTextField and I'm using the KeyPressed
> > method to obtain control over digits and separators entered.
> >
> > Is there a way to obtain the position of the cursor in the field when
> > generating each KeyEvent?
> >
> > when using the following code:
> >    JRNumField jrn_myfield=new JRNumField(6,2, '.');
> >    // creates a numeric textfield with 6 positions and 2 decimals and
'.'
> as
> > separator
> > following valid values can be entered:
> >   1234.56
> >   12.56
> >   1234
> >   ...
> > but also:
> >   12.234
> >   12221.1
> > To resolve this problem I need a way to obtain the position of the
cursor
> > (before or after the separator)
> > Has anybody an idea how to do this or are there some 'home-made'
> components
> > already available with the
> > the same functionality?
> >
> > the code I'm using in keyPressed follows:
> >
> > /**
> >  * This method was created in VisualAge.
> >  * @param ke java.awt.event.KeyEvent
> >  */
> > public void keyTyped(KeyEvent ke) {
> >   // getLength() returns total number of digits
> >   // getDecimals() returns the digits after the separator
> >   // getNotation returns the type of separator (comma or period)
> >   char typedChar=ke.getKeyChar();
> >   int length= getPositions();
> >
> >   // calculate the position of the separator
> >   int pos=getText().indexOf(getNotation());
> >   // set separator to true if separator has allready been entered
> >   boolean separator=pos > -1;
> >
> >   System.out.println("Keyevent=" + ke);
> >
> >   // calculate the maximum total length in characters
> >   // if decimals specified add 1 to total length(separator)
> >   if (getDecimals() > 0) {
> > length++;
> >   }
> >   // logging
> >   System.out.println("Event = " + ke + getText());
> >
> >   // if length of field is equal to maximum length-1
> >   // consume the KeyEvent: throw it away!
> >   if (getText().length() > length-1){
> >   if (getSelectedText().compareTo(getText())==0) {
> >   setText("");
> >   return;
> >   }
> >      System.out.println("String to long");
> >   ke.consume();
> >   return;
> >   }
> >
> >
> >   // test the character being entered
> >   // is character a digit?
> >   else if (Character.isDigit(typedChar))
>
> >   System.out.println("It is a digit!");
> >   // if decimals specified and seperator has been found
> >   if (getDecimals() > 0 && separator) {
> >       int numBefore=pos;
> >   int numAfter=getText().length()- (pos+1);
> >   // is number of digits before or after seperator reached?
> >   // logging
> >   System.out.println("Length= " + getText().length() + "
> > Position= " + pos + " before="+ numBefore + " numAfter=" + numAfter + "
> > decimals=" +getDecimals());
> >   if  (numBefore <= getPositions()-getDecimals() && numAfter
> > <= getDecimals()) {
> >      return;
> >      // !! not correct !!
> >      // !! you need to know the position where the character
> > has been entered...
> >      // !! (where the KeyEvent is being generated)
> >   }
> >   else {
> >   ke.consume();
> >   return;
> >   }
> >   }
> >   else if (getDecimals() > 0 && !separator) {
> >   // if decimals specified and no seperator has been found
> >
> >       if (getText().length() > getPositions()-getDecimals()-1) {
> >   ke.consume();
> >   return;
> >   }
> >   return;
> >   }
> >   }
> >
> >   // is character equal to separator?
> >   else if (ke.getKeyChar()== getNotation() && getDecimals() > 0){
> >   System.out.println("It is a seperator!");
> >   // if seperator has allready been used?
> >   if (separator) {
> >   System.out.println("Separator has already been used");
> >   ke.consume();
> >   }
> >   else {
> >   System.out.println("This is the separator!");
> >     return;
> >   }
> >   }
> >
> >   // no valid character entered
> >   // throw away event
> >   else {
> >   System.out.println("No seperator and no digit!");
> >   ke.consume();
> >   return;
> >   }
> > }
> >
> >
>
> --------------------------------------------------------------------------
> --
> > ----------
> > Geert Van Landeghem
> > Reynders Etiketten
> > gvl@reynderseti.be (Office)
> > hydra@vt4.net (Home)
> > 03/460.12.56 (Office)
> > 0477/759.533 (GSM)
> >
> > <<never play leapfrog with a unicorn>>
>
> --------------------------------------------------------------------------
> --
> > ----------
> >
> >
> >
> > +---
> > | This is the JAVA/400 Mailing List!
> > | To submit a new message, send your mail to JAVA400-L@midrange.com.
> > | To subscribe to this list send email to JAVA400-L-SUB@midrange.com.
> > | To unsubscribe from this list send email to
> JAVA400-L-UNSUB@midrange.com.
> > | Questions should be directed to the list owner: joe@zappie.net
> > +---
>
> +---
> | This is the JAVA/400 Mailing List!
> | To submit a new message, send your mail to JAVA400-L@midrange.com.
> | To subscribe to this list send email to JAVA400-L-SUB@midrange.com.
> | To unsubscribe from this list send email to
JAVA400-L-UNSUB@midrange.com.
> | Questions should be directed to the list owner: joe@zappie.net
> +---
> +---
> | This is the JAVA/400 Mailing List!
> | To submit a new message, send your mail to JAVA400-L@midrange.com.
> | To subscribe to this list send email to JAVA400-L-SUB@midrange.com.
> | To unsubscribe from this list send email to
JAVA400-L-UNSUB@midrange.com.
> | Questions should be directed to the list owner: joe@zappie.net
> +---

+---
| This is the JAVA/400 Mailing List!
| To submit a new message, send your mail to JAVA400-L@midrange.com.
| To subscribe to this list send email to JAVA400-L-SUB@midrange.com.
| To unsubscribe from this list send email to JAVA400-L-UNSUB@midrange.com.
| Questions should be directed to the list owner: joe@zappie.net
+---
+---
| This is the JAVA/400 Mailing List!
| To submit a new message, send your mail to JAVA400-L@midrange.com.
| To subscribe to this list send email to JAVA400-L-SUB@midrange.com.
| To unsubscribe from this list send email to JAVA400-L-UNSUB@midrange.com.
| Questions should be directed to the list owner: joe@zappie.net
+---

As an Amazon Associate we earn from qualifying purchases.

This thread ...

Follow-Ups:

Follow On AppleNews
Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].

Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.