Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

JTextField Difficulty

Posted on 2001-08-07
6
Medium Priority
?
915 Views
Last Modified: 2010-12-01
I need to do following things on a JTextField

1. Make sure only numbers are entered. Meaning that when a user presses a character on the keyboard nothing happens on the JTextField

2. Limit the entry to 4 digits.

3. Not allow -ve values

4. Once a valid value is entered, then on the enter key do something.

Please help me with this. Since I have tried all possible things in my capacity to figure out how to accomplish this.

Thanks In Advance

Bijoy
0
Comment
Question by:bijoyn
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 15

Expert Comment

by:mohan_sekar
ID: 6360092
Hi,

        He is the code I am using to enter only numbers

 
    Put a filtering document in you JTextField is best.
  Here is the class that I use to filter out thing basis on the  
  mask string.
 
  In you application, You only need to do:
 
 
      JTextField jtf = new JTextField(();
      //
      // Only allow numeric 0,1,2,3,4,5,6,7,8,9 to be entered
      //
      jtf.setDocument(new MyTextFilter(MyTextFilter.NUMERIC));
 
  Let me know if you need further help.  Have fun!
 
//
// file MyTextFilter.java
//
import com.sun.java.swing.text.AttributeSet;
import com.sun.java.swing.text.BadLocationException;
import com.sun.java.swing.text.PlainDocument;
 
public class MyTextFilter
  extends PlainDocument
{
  public static final String LALPHA        =
"abcdefghijklmnopqrstuvwxyz";
  public static final String UALPHA        =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  public static final String ALPHA         = LALPHA + UALPHA;
  public static final String NUMERIC       = "0123456789";
  public static final String ALPHA_NUMERIC = ALPHA + NUMERIC;
  public MyTextFilter()
  {
    this(ALPHA_NUMERIC);
  }
  public MyTextFilter(String p_charset)
  {
    m_charset = p_charset;
  }
  public void insertString(int          p_offset,
                           String       p_str,
                           AttributeSet p_attr)
    throws BadLocationException
  {
    if (p_str == null)
      return;
 
    for (int i=0; i<p_str.length(); i++)
      if (m_charset.indexOf(p_str.valueOf(p_str.charAt(i))) == -1)
        return;
     
    super.insertString(p_offset, p_str, p_attr);
  }
 
  /**
   * the allow input character set
   */
  protected String m_charset = null;
}

:-)

bye

Mohan
0
 
LVL 15

Expert Comment

by:mohan_sekar
ID: 6360130
Hi again,


       Here is the code to limit the no. of characters.
---------------------------------

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

public class LimitedPlainDocument extends DFPlainDocument
{
        public LimitedPlainDocument (int maxLength)
        {
                this.maxLength = maxLength;
        }

        private int maxLength;
       
        public final int getMaxLength()
                {
                        return maxLength;
                }
       
        public final void setMaxLength (int maxLength)
                {
                        this.maxLength = maxLength;
                }
       
        public void insertString (int offs, String str, AttributeSet a)
throws
BadLocationException
        {
                if (str == null || getLength() + str.length() <= maxLength)
                            super.insertString (offs, str, a);
                else
                {
                        int remainder = maxLength - getLength();
                        if (remainder > 0)
                                super.insertString (offs, str.substring (0,
remainder), a);
                }
        }
}

call jTextField.setDocument(new LimitedPlainDocument(5));

and u won't be able to enter more than 5 chars even using Clipboard operations.

:-)

bye

Mohan
0
 
LVL 15

Accepted Solution

by:
mohan_sekar earned 1200 total points
ID: 6360180
Hi again,

         Here is the code to filter -ive numbers

import java.awt.Toolkit;

import javax.swing.text.*;


/**
 * Document to only allow numbers.
 * <p>
 * @author Mike Foley
 **/
public class TextFilterDocument extends PlainDocument {

    /**
     * Valid number strings.
     **/
    public static final String NUMBERS = "0123456789";


    /**
     * TextFilterDocument, constructor
     **/
    public TextFilterDocument()
{
        super();
}


    /**
     * 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.
     **/
    public void insertString( int offset, String string,
                              AttributeSet attributeSet )
        throws BadLocationException {

        //
        // 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( NUMBERS.indexOf( string.valueOf(
                string.charAt(i) ) ) == -1 ) {
                   
                //
                // 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 );

    }  // insertString

}  // TextFilterDocument

call the code using the following statement

JTextField integerTextField = new JTextField( new TextFilterDocument() );

I hope I have solved ur problems!!

;-)

bye

Mohan



0
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
LVL 3

Expert Comment

by:rkenworthy
ID: 6360362
here's my simplified solution:

class DocumentListenerExample extends JPanel implements DocumentListener, KeyListener {

  JTextField Field = null;

  public class DocumentListenerExample() {
    Field = new JTextField();
    getContainer().add(Field);
    Field.getDocument().addDocuementListener(this);
    Field.addKeyListener(this);
  }

  public void changeUpdate(DocumentEvent evt) { }

  public void insertUpdate(DocumentEvent evt) {
    removeUpdate(evt);
  }

  public void removeUpdate(DocumentEvent evt) {
    String error = validate(Field.getText());
    if (error != null) {
      //System.out.println("Error: " + error);
      // show dialog or something...
    }
  }

  protected String validate(String text) {
    int num = -1;
    try {
      num = Integer.parseInt(text);
    }
    catch (NumberFormatException e) {
      return e.getText();
    }

    if (num < 0) return "Number cannot be negative.";

    return null;
  }

  public void keyPressed(KeyEvent e) {}
  public void keyReleased(KeyEvent e) {}

  public void keyTyped(KeyEvent e) {
    if ((int) e.getKeyChar() == KeyEvent.VK_ENTER) {
      //DO SOMETHING...
    }
  }

  public static final void main(String args[]) {
    JFrame f = new JFrame();
    f.getContainer().add(new DocumentListenerExample());
    f.pack();
    f.show()
  }
}


I didnt compile this program but should do the trick...

Hope it helps,
Rob
0
 

Author Comment

by:bijoyn
ID: 6360862
Hi Mohan & Rob

Thanks for the solutions. The difference between the two solutions are many. As I had specified. I wanted to restrict the user to input only 4 characters ( which Mohan gave me a solution ). The second was to input only numeric
values to the same textfield. this though Mohan has given me the solution. I am not sure how to combine the 1st and the second requirement together because u can setDocument to one class at a time. Also Mohan once u set the textfield to be numeric, u need not write the code for -ve numbers or do we ?.

Rob your solution allows me to enter non-numeric which is validated later. This is not what I wanted.

Mohan can u tell me how to combine the NUMERIC and the MAXLENGTH together in one Document class

Appreciate it.

Bijoy
0
 

Author Comment

by:bijoyn
ID: 6361059
Mohan,

I could combine the two functionalities within the same class and thanks a lot for your help.

Bijoy.
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

688 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