This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Set a new document model
Posted by Kishori Sharan on February 08, 2002 at 10:24 AM
You need to create a text field class inheriting from JTextField and then override createDefaultModel method. In that method you need to return an object which extends PlainDocument and override the insertString method. I have included an example. Compile and run TextTest.java and it will demonstrate what you want. In example I have set maximum chars to 5. Thanks Kishori /////////////// TextTest.java file import javax.swing.* ; import javax.swing.text.* ; public class TextTest extends JFrame { MyJTextField t1 = new MyJTextField ( 20 ) ; public TextTest ( ) { // set the maximum chars to 5 t1.setMaxCharacters ( 5 ) ; this.getContentPane().add ( t1, "North" ) ; } public static void main ( String[] args ) { TextTest t = new TextTest ( ) ; t.setBounds ( 50, 50, 300, 300 ) ; t.show() ; } } class MyJTextField extends JTextField { private int maxChars = 50 ; // By default set the max chars to 50 public MyJTextField (int cols) { super(cols); } public void setMaxCharacters ( int maxChars ) { if ( maxChars < 0 ) { this.maxChars = 0 ; } else { this.maxChars = maxChars ; } } protected Document createDefaultModel() { return new PlainDocument ( ) { public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } // Get the length of the text in JTextField int len = 0 ; if ( MyJTextField.this.getText() == null ) { len = 0 ; } else { len = MyJTextField.this.getText().length() ; } if ( len + str.length() > MyJTextField.this.maxChars ) { // Total chars will be more than max allowed. So, just return return ; } else { // Update the text field super.insertString(offs, str, a); } } } ; } }
Replies:
|