?
Solved

input for text field

Posted on 2004-10-09
11
Medium Priority
?
359 Views
Last Modified: 2010-03-31
Hi experts,

I need code to let the user enter a name into a text field. I want the name to be at least 3 words...also want the text field to accept only letters,spaces and dots and small dash -

thanks
0
Comment
Question by:Samooramad
[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
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 3

Assisted Solution

by:CI-Ia0s
CI-Ia0s earned 80 total points
ID: 12268443
Hrmmm... that's complicated. You can use JOptionPane to get the input (make sure to put "import javax.swing.*;" at the top of your file):

String nameString = JOptionPane.showInputDialog("Enter a name 3 words long with only letters, periods, spaces, and dashes:");

For making sure it's 3 words at least:

int startPoint = nameString.indexOf(" ");
if (startPoint > -1){
startPoint = nameString.indexOf(" ", (startPoint + 1));
}
else{
//Make them enter it again
}
if (startPoint > -1){
startPoint = nameString.indexOf(" ", (startPoint + 1));
}
else{
//Make them enter it again
}
if (startPoint > -1){
//Do nothing or call a method to proceed
}
else{
//Make them enter it again
}

For making sure it's only letters, spaces, dots, and the dash symbol, do this:
nameString = nameString.toLowerCase();
for (int c = 0; c < nameString.length(); c++){
if (nameString.charAt(c) != 'a' || nameString.charAt(c) != 'b' || nameString.charAt(c) != '.' || nameString.charAt(c) != '-'){
//Make 'em do it again
}

Of course you'll have to have != 'c', d, e, f, etc.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12268445
// Create a text field with some initial text
    JTextField textfield = new JTextField("Initial Text");
   
    // Create a text field with some initial text and a default number of columns.
    // The number of columns controls the preferred width of the component;
    // each column is rougly the size of an M in the current font.
    int cols = 30;
    textfield = new JTextField("Initial Text", cols);
   
    // Listen for action events, which are fired when the user hits RETURN
    textfield.addActionListener(new MyActionListener());
   
    class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            JTextField textfield = (JTextField)evt.getSource();
            if(!valid(textfield.getText()))textfield.setText("");
        }
if (str == null ) {
      return false;
    }
    boolean ok = true;
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        ok = true;
      }
      else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
        ok = true;
      }
      else if (str.charAt(i) == '.' || str.charAt(i) == '-' || str.charAt(i) == ' ') {
        ok=true;
      }
      else {
        ok = false;
        break;
      }
    }
    java.util.StringTokenizer st=new  java.util.StringTokenizer(str);
    if(ok)
    {
      ok = st.countTokens() > 3 ? false : true;
    }

    return ok;
  }
       
    }
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12268464
Yup. That'd be more efficient. I forgot you could use characters as integers... ;)
0
Technology Partners: 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!

 

Author Comment

by:Samooramad
ID: 12268518
thanks CI-Ia0s :)  your help is appretiated

sudhakar can I ask you two questions?
Are the columns meant for sizing the textfield?
what does valid do?
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12268535
columns is to set the length of textField text;
valid checks the text as per your requirements.
if it is not matched return false otherwise true

now based on the text entered , if it is not valid then  just resets the text to null string
0
 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 520 total points
ID: 12268537

class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            JTextField textfield = (JTextField)evt.getSource();
            if(!valid(textfield.getText()))textfield.setText("");
        }


 public boolean valid(String str) {
    if (str == null) {
      return false;
    }
    boolean ok = true;
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        ok = true;
      }
      else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
        ok = true;
      }
      else if (str.charAt(i) == '.' || str.charAt(i) == '-' ||
               str.charAt(i) == ' ') {
        ok = true;
      }
      else {
        ok = false;
        break;
      }
    }
    java.util.StringTokenizer st = new java.util.StringTokenizer(str);
    if (ok) {
      ok = st.countTokens() > 3 ? false : true;
    }

    return ok;
  }
}

0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 12270402
Try

String s = "Madam I'm Adam";
final String RE1 = "[A-Za-z \\.\\-]+";
final String RE2 = "[^ ]+[ ]+[^ ]+[ ]+[^ ]+";

boolean valid = (s.matches(RE1) && s.matches(RE2));
0
 
LVL 92

Expert Comment

by:objects
ID: 12272969
If you use a custom Document for your text field (subclass PlainDocument) you can stop invalid characters even being entered in the text field removing the need for checking for them.
0
 
LVL 92

Expert Comment

by:objects
ID: 12272984
import javax.swing.text.*;

public class MyDocument extends PlainDocument
{
    public void insertString(int offset, String s, AttributeSet attributeSet)
        throws BadLocationException
    {
        // check for valid characters here
    }
}

0
 

Author Comment

by:Samooramad
ID: 12273037
ok Im working on it :)
0
 

Author Comment

by:Samooramad
ID: 12273516
ok sudhakar's and CEHJ's code worked great. I wasn't exactly sure what you meant objects so didnt get that working

thank you
0

Featured Post

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month13 days, 13 hours left to enroll

801 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