[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Accepting only letters and spaces in JTextField

Posted on 2004-05-02
11
Medium Priority
?
1,560 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 200 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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…
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…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

650 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