Solved

Accepting only letters and spaces in JTextField

Posted on 2004-05-02
11
1,220 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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
noX challenge 17 76
mapAB Challlenge 35 85
Running Jira on Raspberry PI 2? 3 127
JAVA part two 5 41
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

705 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

19 Experts available now in Live!

Get 1:1 Help Now