Solved

Accepting only letters and spaces in JTextField

Posted on 2004-05-02
11
1,414 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
[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
  • 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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 
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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

696 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