0

I'm working on a Java Swing application that involves the use of JTextField for user input. I want to restrict the minimum and maximum length of text that users can enter into the JTextField component. However, the standard JTextField does not provide a built-in method to set such a limit, and i'm looking for a way to implement this functionality to ensure that users cannot input more digits than the specified limit. Minimum & Maximum = 6 digits

Problem solved with this code

max.setDocument(new Limit(6)); Limit as New Class

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

class Limit extends PlainDocument {

    private static final long serialVersionUID = 1L;
    private int limit;

    public Limit(int limit) {
        this.limit = limit;
    }

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

        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        }
    }
}
Hellthinky
  • 11
  • 7
  • 2
    Oracle has a helpful tutorial, [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html). Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the [Text Component Features](https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html) section under Implementing a Document Filter. – Gilbert Le Blanc Aug 28 '23 at 03:24
  • 2
    Use a JFormattedTextField. You can specify a mask which will limit the number of characters and the type of characters. – camickr Aug 28 '23 at 03:42
  • would you share the code? – Hellthinky Aug 28 '23 at 03:58
  • 2
    Using an [InputVerifier](https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#inputVerification) may also be appropriate. – Abra Aug 28 '23 at 04:01
  • 1
    The tutorial has lots of code to be shared. – camickr Aug 28 '23 at 20:14

0 Answers0