Set Max Character Length Of JTextField


There is no way to directly set a JTextField‘s maximum character length. The only way for you to do that is to create your own class that inherits the PlainDocument class, instantiate an object of that class and call the JTextField method setDocument().

Below is the source for the custom made MaxLengthTextDocument class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MaxLengthTextDocument extends PlainDocument {
    private int maxChars;
 
    public MaxLengthTextDocument(int length) {
        maxChars = length;
    }
 
    @Override
    public void insertString(int offs, String str, AttributeSet a)throws BadLocationException {
        if(str == null || (getLength() + str.length() > maxChars)){
            str = str.substring(0, maxChars);
        }
        super.insertString(offs, str, a);
    }
}

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Set TextField To Accept Numbers Only In Java


Having a TextField accept only numeric values can be done easily by modifying your own PlainDocument class and setting an instance of it in the TextField‘s setDocument() method. Rather than creating listeners to the TextField itself, using an inherited Document class requires you to use only one line of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class NumericDocument extends PlainDocument {
     //Variables
     protected int decimalPrecision = 0;
     protected boolean allowNegative = false;
 
     public NumericDocument() {
         super();
     }
 
     public NumericDocument(int decimalPrecision, boolean allowNegative) {
          super();
          this.decimalPrecision = decimalPrecision;
          this.allowNegative = allowNegative;
     }
 
     //Insert string method
     @Override
     public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
          if (str != null){
               if (!StringTool.isNumeric(str) && !str.equals(",") && !str.equals("-")){ //First, is it a valid character?
                    Toolkit.getDefaultToolkit().beep();
                    return;
               }
               else if (str.equals(",") == true && super.getText(0, super.getLength()).contains(",")){ //Next, can we place a decimal here?
                    Toolkit.getDefaultToolkit().beep();
                    return;
               }
               else if (StringTool.isNumeric(str) && super.getText(0, super.getLength()).indexOf(",") != -1 && offset>super.getText(0, super.getLength()).indexOf(",") && super.getLength()-super.getText(0, super.getLength()).indexOf(",")>decimalPrecision && decimalPrecision > 0){ //Next, do we get past the decimal precision limit?
                    Toolkit.getDefaultToolkit().beep();
                    return;
               }
               else if (str.equals("-") == true && (offset != 0 || allowNegative == false)){ //Next, can we put a negative sign?
                    Toolkit.getDefaultToolkit().beep();
                    return;
               }
 
               //All is fine, so add the character to the text box
               super.insertString(offset, str, attr);
          }
          return;
     }
}

To use the class, do this:

1
2
JTextField tf = new JTextField();
tf.setDocument(new NumericDocument());

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

JTextField selectAll() And DefaultCellEditor


I am guessing this is quite a common problem that programmers encounter when they have JTextField objects inside a JTable. When you click on a cell, it would not select all the text in it. You have to double click it first. Even the DefaultCellEditor’s setClickCountToStart(1) method does not help. The workaround for this is to override the shouldSelectCell() method.

1
2
3
4
5
@Override
public boolean shouldSelectCell(EventObject eo) {
    ((JTextField) getComponent()).selectAll();
    return super.shouldSelectCell(eo);
}

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails