Search code examples
javaeclipsemacosswingjtextfield

How does java limit text fields?


EDIT: I didn't ask for the syntax on how to set the number of characters. I can find that easily in a simple search. Please read and understand before downvoting someone. I was asking how to find where this is in the source code based ont he code below. I found it on my own using the "Reference" feature, which directed me to the other classes which called the JTextFieldLimit class.

END EDIT.

I'm trying to edit the source code for an app someone built for me. The login field is limited to 15 characters but I need to increase this. After some googling, the closest I've come so far is the code inside the JTextFieldLimit class, which is as follows:

package app;

import javax.swing.text.*;

//import javax.swing.text.*;
public class JTextFieldLimit extends PlainDocument {
  private int limit;
  // optional uppercase conversion
  private boolean toUppercase = false;

  JTextFieldLimit(int limit) {
   super();
   this.limit = limit;
   }

  JTextFieldLimit(int limit, boolean upper) {
   super();
   this.limit = limit;
   toUppercase = upper;
   }

  public void insertString
    (int offset, String  str, AttributeSet attr)
      throws BadLocationException {
   if (str == null) return;

   if ((getLength() + str.length()) <= limit) {
     if (toUppercase) str = str.toUpperCase();
     super.insertString(offset, str, attr);
     }
   }
}

Where do I go from here?


Solution

  • According to Limiting the number of characters in a JTextField, you call the setDocument method of JTextField with the JTextFieldLimit as a parameter. I can't verify that it works, only that it is the highest-voted answer for that question.