Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

How do I limit the No. of Chars in the TextField ?

The database field size is 5 chars. But, user can enter more than 5 chars in the text field in an applet. I can do edit check and display a message. But, I want to limit entering the 6th char. Is there any way ?

I can use only AWT components.

Thanks.
0
UU1
Asked:
UU1
  • 3
1 Solution
 
dvijiCommented:
Hi UU1!
     We can do it by using the keyListener. In the KeyListener's  KeyTyped() method you can do your validation. Here check the length of the string in the textfield using textfield.getText() if it is greaterthan 5 then do textfield.setText(oldText). For TextField if you create your own class " FilteredTextField which extends TextField" and implement the KeyListener. So that you can have your own properties and validation in thid class. It will be resuable also.

...dviji
0
 
a.marshCommented:
I've just put this together for you:

import java.awt.*;
import java.awt.event.*;

class AntTest{
     Frame mainFrame;
     Panel mainPanel;
     MaxTextField textField;

     public AntTest(){
       mainFrame = new Frame("MaxTextField Test");
       mainFrame.setSize(200,100);

       mainPanel = new Panel();

       textField = new MaxTextField(10, 6);

       mainPanel.add(textField);

        mainFrame.add(mainPanel);

       mainFrame.show();
     }

     public static void main(String[] args){
       AntTest myAntTest = new AntTest();
     }
}

class MaxTextField extends TextField implements KeyListener{

     private int maxLength;

     public MaxTextField(int cols, int maxLength){
       super(cols);
       this.maxLength = maxLength;
       this.addKeyListener(this);
     }

     public void keyPressed(KeyEvent ke){
       String currText = getText();
       if(currText.length() >= maxLength && ke.getKeyCode() != ke.VK_BACK_SPACE){
         ke.setKeyCode(ke.VK_CANCEL);
       }
     }
     public void keyTyped(KeyEvent ke){
     }
     public void keyReleased(KeyEvent ke){
     }
}


Compile it and run it to see it in action.

:o)

Ant
0
 
a.marshCommented:
Sorry dviji, I've only just seen your comment - great minds think alike though!

:o)

Ant
0
 
UU1Author Commented:
Thanks March. Appreciate.
0
 
a.marshCommented:
Glad to help.

:o)

Ant
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now