Solved

input for text field

Posted on 2004-10-09
11
335 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

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

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Application launch issue with Apache Tomcat 5 44
Apps blocked by Java 9 79
replace a word with other 1 44
What's wrong with this code? 4 23
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
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 will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
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 …

770 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