设置TextField的宽度

Elj*_*jay 1 java swing jtextfield

我想设置TextField可以使用的最大条目数,我用过:

setMaximumSize
setPreferredWidth
SetColumns
Run Code Online (Sandbox Code Playgroud)

但是无法这样做.我怎么能完成它?

这是我的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

wmz*_*wmz 5

使用DocumentFilter,如本教程中的Oracle doc过滤器教程中所述

以下是我最近用于限制框中最大条目大小和char类的内容:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

您也可以InputVerifier在离开输入字段之前检查输入.(提示:如何确保输入正好是 n个字符?)