how to Restrict jFormattedTextField
I have a jFormattedTextFiled for field "Name". I have to restrict the field to enter only 25characters. 开发者_Python百科if entered more some message has to be displayed... for message I can use JOptionpane..
How can I do it?
Using a KeyStrokeListener would be a bad idea, as it would fire an event even when non-writable keys like SHIFT, arrows and the such are pressed.
By using the constructor using a Format, you can first ensure that only the 25 first characters will be displayed and entered (as an example using a MaskFormatter, like told in Java Tutorial).
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.
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);
}
精彩评论