Solved

input for text field

Posted on 2004-10-09
11
342 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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

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 …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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 how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

856 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