Solved

Accepting only letters and spaces in JTextField

Posted on 2004-05-02
11
1,240 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
wordappend challenge 8 143
maven project error 5 47
couple of eclipse 5 16
reverse digits of a number using for loop 5 36
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

932 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now