Search code examples
javaswingjtextfield

Setting the width of TextField


I want to set the maximum number of entries a TextField can take, I used:

setMaximumSize
setPreferredWidth
SetColumns

but was not able to do so. How can I accomplish it?

Here is my code:

import java.awt.*;
import javax.swing.*;
public class ButtonDemo extends JFrame {

    public static void main(String args[]){
        JFrame jfrm = new JFrame("Sample program");
        Container Content =  jfrm.getContentPane(); 
        content.setBackground(Color.red);
        jfrm.setLayout(null);

        jfrm.setBounds(250, 150, 400, 400);
        JTextField text = new JTextField();
        Font font1 = new Font("Courier",Font.BOLD,12);
        text.setFont(font1); 
        text.setBounds(50, 15, 100, 30);

        JButton button1 = new JButton("PROGRAM"); 
        button1.setFont(font1);
        button1.setBounds(250, 15, 100, 40);
        button1.setBackground (Color.white);

        JButton button3 = new JButton("EXIT");
        button3.setBounds(250, 115, 100, 40);
        button3.setBackground (Color.cyan);
        button1.setForeground (Color.red);

        JButton button2 = new JButton("USER"); 
        button2.setBounds(250, 65, 100, 40);
        button2.setBackground (Color.WHITE);

        jfrm.add(button1);  
        jfrm.add(button2); 
        jfrm.add(button3); 
        jfrm.add(text); 

        jfrm.setVisible(true);  
        jfrm.setResizable(false);
    }
}

Solution

  • Use DocumentFilter, as explained in this tutorial Oracle doc filter tutorial

    Here is for example what I recently used to limit both max entry size and class of char in the box:

    class SizeAndRegexFilter extends DocumentFilter {
      private int maxSize;
      private String regex;
    
      SizeAndRegexFilter (int maxSize,String regex) {
        this.maxSize=maxSize;
        this.regex=regex;
    
      } 
      public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException {
        if ((fb.getDocument().getLength() + str.length()) <= maxSize && str.matches(regex))
            super.insertString(fb, offs, str, a);
        else
            Toolkit.getDefaultToolkit().beep();
      }
    
      public void replace(FilterBypass fb, int offs,int length, String str, AttributeSet a) throws BadLocationException {
        if ((fb.getDocument().getLength() + str.length()
                 - length) <= maxSize  && str.matches(regex))
                super.replace(fb, offs, length, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
      }
    }
    

    You may also use InputVerifier to check your input before leaving the input field. (hint: how to make sure your input is exactly n characters?)