tags:

views:

34

answers:

3

Hi All,

I have a jFormattedTextFiled for field "Name". I have to restrict the field to enter only 25characters. if entered more some message has to be displayed... for message i can use JOptionpane..

how can i do it.. please help me to solve it..

Thanks in advanced

+2  A: 

Using a KeyStrokeListener would be a bad idea, as it would fire an event even when non-writable keys like SHIFT, arraows and the such are pressed.

By using the constructor using a Format, you can first ensure that only the 25 first cahracters will be displayed and entered (as an example using a MaskFormatter, like told in Java Tutorial).

Riduidel
I was on the wrong track. This is how it works for formattet text fields.
Andreas_D
A: 

Hi, i hope this will also works

Add keylistener to the concerned textfield and in the keypressed event write the following code

JTextField jTextField1=new JTextField();

jTextField1.setText(""); //intially the textfield is empty

void jTextField1_keyPressed(KeyEvent e) {

    int len=jTextField1.getText().length();

    System.out.println("hello1::"+len);

    jTextField1.setEditable(len <= 24);
}
charan
This is not a good approach. The user can be pasting text into the text field which can contain multiple characters. Also, once the text field is full and you make the field non-editable, how does the user edit the field to remove characters if a typing mistake was made?
camickr
+1  A: 

Using a JFormattedTextField won't allow you to display a JOptionPane with a message as you will hear a beep when you attempt to enter extra characters. However, this is probably the more common approach rather than displaying a popup every time.

However, if you really want a popup then you need to use a DocumentFilter. The section from the Swing tutorial on Implementing a Document Filter gives an example of doing what your want. All you need to do is replace the "beep" code to display a popup.

camickr