Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict the JTextField to a x number of characters

I have to restrict the number of characters in the JTextField. I used the following code to do that but the problem is i am feeding the data to JTextField using the virtual keyboard. So the offset is set to 0 all the time. When i enter more than the specified number of characters it resets the field and start doing it from the beginning. For example if my limit is 3 characters and i am entering xyz0 my limited textbox reads the character upto z and then clears the field and restart again. So i am left with 0 in the field. The code is as follows.

  public class JTextFieldLimit extends PlainDocument {
  private int limit;  
  public JTextFieldLimit(int limit) {  
   super();  
   this.limit = limit;  
   }  
    @Override  
  public void insertString( int offset, String  str, AttributeSet attr ) throws   BadLocationException {  
    if (str == null) return;  
            System.out.println("from document helper getLength():"+getLength());  
            System.out.println("from document helper str.length():"+str.length());  
            System.out.println("from document helper str:"+str);  
            System.out.println("from document helper attr:"+attr);  
            System.out.println("from document helper offset:"+offset);  
    if ((getLength() + str.length()) <= limit) {  
      super.insertString(offset, str, attr);  
    }  
  }  
}  
like image 810
Deepak Avatar asked May 30 '11 04:05

Deepak


People also ask

How do I limit the number of characters in a JTextField?

We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.

How do I make JTextField Uneditable?

To make JTextField read only or non editable use, void setEditable(boolean editable) method with false argument.

How do I make JTextField smaller?

you can do one thing : put your jtextfield within a JPanel, now that JPanel is the one which will have large size, but that won't be visible and then you can control the layout of JPanel and hence you can control the size of the jtextfield. We don't care about your project, only the part you are having problems with.


1 Answers

You should use a DocumentFilter as per this tutorial. For example:

import javax.swing.*;
import javax.swing.text.*;

public class JTextFieldLimit2 extends JPanel{
   JTextField textfield = new JTextField(5);

   public JTextFieldLimit2() {
      PlainDocument doc = (PlainDocument) textfield.getDocument();
      doc.setDocumentFilter(new TextLengthDocFilter(3));

      add(textfield);
   }

   private class TextLengthDocFilter extends DocumentFilter {
      private int maxTextLength;

      public TextLengthDocFilter(int maxTextLength) {
         this.maxTextLength = maxTextLength;
      }

      private boolean verifyText(String text) {
         return text.length() <= maxTextLength;
      }

      @Override
      public void insertString(FilterBypass fb, int offset, String string,
               AttributeSet attr) throws BadLocationException {

         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);
         sb.insert(offset, string);

         if (verifyText(sb.toString())) {
            super.insertString(fb, offset, string, attr);
         }

      }

      @Override
      public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
               throws BadLocationException {
         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);

         sb.replace(offset, offset + length, text);
         if (verifyText(sb.toString())) {
            super.replace(fb, offset, length, text, attrs);
         }
      }

      @Override
      public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);

         sb.replace(offset, offset + length, "");

         if (verifyText(sb.toString())) {
            super.remove(fb, offset, length);            
         }
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("JTextFieldLimit2");
      frame.getContentPane().add(new JTextFieldLimit2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
like image 180
Hovercraft Full Of Eels Avatar answered Nov 10 '22 00:11

Hovercraft Full Of Eels