Java method to count the characters of a string

44,404

You must get the text from your GUI-component first:

private javax.swing.JTextField jTextField;

String text = jTextField.getText();
int counter = text.length();

JTextField itself is a GUI-Component and not a String. But getText() method gives you the text entered in this component as a String which you can then use to determine the length.

Share:
44,404
Studie
Author by

Studie

Student in Software Engineering, currently in the 6th semester. Newbie in programming Experiences in c, c++, obj-c, python, java, (x)html(5), css, XAMPP and Joomla.

Updated on February 27, 2020

Comments

  • Studie
    Studie about 4 years

    I have a string named text and I want to count the number of its characters. But there is no method 'count' like in ObjC.

    In the Internet I found the method 'length', which could be useful. But If I write:

    private javax.swing.JTextField txtText;
        int counter = txtText.length();
    

    the compiler complains: "cannot find the symbol"

    I thought I need a framework to include, I am absolutely new in Java.

    • Louis Wasserman
      Louis Wasserman about 12 years
      This should work. Can you show us the declaration of text?
    • Jeffrey
      Jeffrey about 12 years
      Where's the rest of your code? This is probably a scope problem.
    • Hovercraft Full Of Eels
      Hovercraft Full Of Eels about 12 years
      Please show the actual error message as your question is missing a lot of important details. Also, show the code above and below this line and let us know where this line of code is located. Is it in a method or constructor? I'll bet that you have this line hanging out naked in the class and not enclosed in a method, constructor, or other similar block. Or else as others have stated, your text variable is out of scope, but right now until you supply the details needed you're making us guess which isn't playing nice.
    • JB Nizet
      JB Nizet about 12 years
      Show us the rest of your code, so that we at least know what the type of text is. And don't google for information about class methods, but read their javadoc: download.oracle.com/javase/6/docs/api
    • scheibk
      scheibk about 12 years
      You don't have any code that gets the text from your text field. If you are, then it is probably a scope problem. If you aren't then that is probably the problem.