Can someone help me please. I am using a Scanner Class and want to count characters entered in the textfield. Unfortunately, backspace and any key (Ctr,Alt,Capslock) for that matter is counted as a character and that increments the counter by 1.

Here is the code

String ab="^[A-Za-z0-9]+$";

    public void keyReleased(KeyEvent ke) throws NoSuchElementException{
                           Scanner scann=new Scanner(Jtextfield.getText());
                                  
   {
   String sarwa=scann.next(ab);

   if(true)


    i++;
    champo.setText("  "+Integer.toString(i));

   }

Thankyou,
ARZ

Does it also count the previous character entered?

yes it does

Do you have a small test program with a text field that compiles and executes to demonstrate the problem?

Since the previous character (the one erased) and the backspace are both counted, then the input stream must be in "raw" as opposed to "cooked" mode. Basically, you need to change the input attributes so that the backspace really removes the previous character from the string/stream. If it doesn't, then you will need to create a callback to handle that for you.

Can you please elaborate a little, How should i change the input attributes?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.