Solved

input for text field

Posted on 2004-10-09
11
318 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
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 3

Assisted Solution

by:CI-Ia0s
CI-Ia0s earned 20 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
 

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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 130 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 50 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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 will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

747 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

13 Experts available now in Live!

Get 1:1 Help Now