Solved

Accepting only letters and spaces in JTextField

Posted on 2004-05-02
11
1,305 Views
Last Modified: 2012-08-14
public class AlphaDocument extends PlainDocument {

      public AlphaDocument(){
            super();
      }
      
      public void insertString(int offset, String s, AttributeSet attributeSet)
             throws BadLocationException{
             
             char[] inputChars = s.toCharArray();
             try{
                    for(int i = 0; i < inputChars.length; i++){
                        if(Character.isLetter(inputChars[i]) || inputChars[i] == ' '){
                              super.insertString(offset, s, attributeSet);
                        }
                        else{
                              Toolkit.getDefaultToolkit().beep();
                        }

                    }

                          
             }
             catch (Exception ex){
                    Toolkit.getDefaultToolkit().beep();
             }

      }

}

this works, but not when pasting a string into the text field.  also, how can i optionally limit the text length?
0
Comment
Question by:abstractionz
  • 4
  • 3
  • 2
  • +1
11 Comments
 

Author Comment

by:abstractionz
ID: 10971671
public class AlphaDocument extends PlainDocument {
      
      private int limit = 0;
      
      public AlphaDocument(){
            super();
      }
      
      public AlphaDocument(int limit){
            super();
            this.limit = limit;
      }
      
      public void insertString(int offset, String s, AttributeSet attributeSet)
             throws BadLocationException{
             char[] inputChars = s.toCharArray();
             boolean success = false;
             try{
                    for(int i = 0; i < inputChars.length; i++){
                        if(Character.isLetter(inputChars[i]) || inputChars[i] == ' '){
                              success = true;
                        }
                        else{
                              success = false;
                              break;
                        }
                    }
                    
                    if(success && limit == 0 || this.getLength() + s.length() <= limit){
                        super.insertString(offset, s, attributeSet);
                    }
                    else{
                        Toolkit.getDefaultToolkit().beep();
                    }
                          
             }
             catch (Exception ex){
                    Toolkit.getDefaultToolkit().beep();
             }

      }

}

this works fine until i enter a limit for the text, then it allows numbers.
0
 
LVL 7

Expert Comment

by:maheshexp
ID: 10971741
Customized fields can easily be created by extending the model and changing the default model provided. For example, the following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard or it is altered via programmatic changes.



 public class UpperCaseField extends JTextField {
 
     public UpperCaseField(int cols) {
         super(cols);
     }
 
     protected Document createDefaultModel() {
             return new UpperCaseDocument();
     }
 
     static class UpperCaseDocument extends PlainDocument {
 
         public void insertString(int offs, String str, AttributeSet a)
                 throws BadLocationException {
 
                 if (str == null) {
                   return;
                 }
                 char[] upper = str.toCharArray();
                 for (int i = 0; i < upper.length; i++) {
                   upper[i] = Character.toUpperCase(upper[i]);
                 }
                 super.insertString(offs, new String(upper), a);
             }
     }
 }

0
 
LVL 7

Expert Comment

by:maheshexp
ID: 10971749
0
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.

 
LVL 5

Expert Comment

by:twobitadder
ID: 10972001
maheshexp, I'm not sure if you know or not but the website listed on your profile has an encrypted polymorphic activex vb virus embedded in one of the compiler pages, page6 at the bottom.
0
 
LVL 5

Expert Comment

by:twobitadder
ID: 10972033
it's also in page16.htm
0
 
LVL 7

Expert Comment

by:maheshexp
ID: 10972035
twobitadder, very much thanks for the info...yeah i didn't know abt it...i will remove it...
0
 

Author Comment

by:abstractionz
ID: 10972717
maheshexp,

thanks for the general information but i already know about formattedtextfields.  i posted my code because there was a bug in it, which i found.  the problem was in the conditional.  i changed it to:

if(success && (limit == 0 || this.getLength() + s.length() <= limit)){
0
 
LVL 92

Expert Comment

by:objects
ID: 10974004
>   super.insertString(offset, s, attributeSet);

you insert the entire string everytime you find a valid char.
Instead you should be only inserting the valid char.

Alternatively you may want to only insert the string if *all* chars are valid.
0
 

Author Comment

by:abstractionz
ID: 10974061
> Alternatively you may want to only insert the string if *all* chars are valid.

isn't that what i'm doing in my 2nd posting?
0
 
LVL 92

Accepted Solution

by:
objects earned 50 total points
ID: 10974075
It is, sorry didn't look at that closely.

you problem there is in your test:

if(success && limit == 0 || this.getLength() + s.length() <= limit){

should be:

if(success && (limit == 0 || this.getLength() + s.length() <= limit)){
0
 

Author Comment

by:abstractionz
ID: 10974085
yea that's what i realized 4 posts up.  thanks though.
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
check java version using powershell 13 168
by zero exception 10 52
String array comparison 4 38
Convert from a json string array to a Java object 3 51
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

809 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