Eljay
Eljay

Reputation: 951

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);
    }
}

Upvotes: 1

Views: 4994

Answers (5)

nIcE cOw
nIcE cOw

Reputation: 24616

I had modified your program a bit for your thing to work, do have a look :

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

    public static void main(String args[]){
        JFrame jfrm = new JFrame("Sample program");
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrm.setLocationByPlatform(true);
        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);

        AbstractDocument abdoc;
        Document doc = text.getDocument();
        if (doc instanceof AbstractDocument)
        {
            abdoc = (AbstractDocument) doc;
            abdoc.setDocumentFilter(new DocumentSizeFilter(4));
        }

        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);
    }
}

class DocumentSizeFilter extends DocumentFilter {

   private int max_Characters;
   private boolean DEBUG;

   public DocumentSizeFilter(int max_Chars) {

      max_Characters = max_Chars;
      DEBUG = false;
   }

   public void insertString(FilterBypass fb
                            , int offset
                              , String str
                                , AttributeSet a) 
   throws BadLocationException {

      if (DEBUG) {

         System.out.println("In DocumentSizeFilter's insertString method");
      }

      if ((fb.getDocument().getLength() + str.length()) <= max_Characters) 
         super.insertString(fb, offset, str, a);
      else 
         Toolkit.getDefaultToolkit().beep();
   }

   public void replace(FilterBypass fb
                       , int offset, int length
                       , String str, AttributeSet a)
   throws BadLocationException {

      if (DEBUG) {

         System.out.println("In DocumentSizeFilter's replace method");
      }
      if ((fb.getDocument().getLength() + str.length()
           - length) <= max_Characters) 
         super.replace(fb, offset, length, str, a);
      else
         Toolkit.getDefaultToolkit().beep();
   }
}

Simply add here, abdoc.setDocumentFilter(new DocumentSizeFilter(4)); the Maximum number of Characters you wanted that JTextField to have. Replace 4 with any number of your choice.

Hope this might help in some way.

Regards

Upvotes: 1

wmz
wmz

Reputation: 3685

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?)

Upvotes: 6

Sam Palmer
Sam Palmer

Reputation: 1725

The problem is your layout manager is still taking charge of the layout hence, setMaximumSize setPreferredWidth do not work.

To fix this at the start you need to set the layout manager to null.

jfrm.setLayout(null);

Though by doing this you will need to use absolute positioning of the components.

Also see Java, Swing: how do I set the maximum width of a JTextField?

Upvotes: 0

Marcelo
Marcelo

Reputation: 4608

Apart from using a different Document as suggested by Thomas, you can also use a FormattedTextField. Might be easier.

Upvotes: 2

Thomas
Thomas

Reputation: 88707

The textfield itself doesn't restrict the length of the text. To get what you want you'd have to provide a different document to the textfield, either by calling setDocument() or by passing it to the constructor.

Your document would be an instance of javax.swing.text.Document, e.g. a subclass of javax.swing.text.PlainDocument. Then override the public void insertString(int offs, String str, AttributeSet a) throws BadLocationException method.

Swing seems to have a FixedLengthDocument, however that's a private static inner class of HTMLDocument. However, to get you started, here's the relevant part of that class' source:

public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
  if (str != null && str.length() + getLength() <= maxLength) {
    super.insertString(offset, str, a);
  }
}

Upvotes: 2

Related Questions