当前位置: 代码迷 >> Java相关 >> 如限制JTextField的输入个数?
  详细解决方案

如限制JTextField的输入个数?

热度:468   发布时间:2008-06-01 14:16:09.0
如限制JTextField的输入个数?
如只想让用户最大输入16个字符,即当输入第17个字符时,就无法输入.这该如何实现?
搜索更多相关的解决方案: JTextField  输入  

----------------解决方案--------------------------------------------------------
回复 1# y218z903 的帖子
你限制了最大的输入字符数,提交时,多余的字符应该会舍弃。另外,可以给JTextField的长度加一个事件监听,搞个弹出窗口提示下!
----------------解决方案--------------------------------------------------------
有没有更好的方法?
----------------解决方案--------------------------------------------------------
js不就可以了?
----------------解决方案--------------------------------------------------------
这个也许是你想要的
public class Input extends javax.swing.JFrame {
    private String limit1="[0-9]",limit2="[a-h]";
    /** Creates new form Input */
    public Input() {
        initComponents();
        CheckInput c1=new CheckInput();
        c1.setCharLimit(limit1);     //设置输入范围
        c1.setMaxLength(5);          //设置输入的最大长度
        c1.setMaxValue(10000);       //设置输入的最大数字
        jTextField1.setDocument(c1);
        
        CheckInput c2=new CheckInput();
        c2.setCharLimit(limit2);
        c2.setMaxLength(7);
        jTextField2.setDocument(c2);
        
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("可以输入0到9之间的数字5个,最大值为10000,不正确或超出长度均报警");

        jLabel2.setText("请输入");

        jLabel3.setText("可以输入a到h之间的字母7个,不正确或超出长度均报警");

        jLabel4.setText("请输入");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

   
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Input().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration

}


import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.Toolkit;
import java.util.regex.Pattern;


public class CheckInput extends PlainDocument {
    private String limit = null; // 输入字符限制的正则表达式
    private int maxLength = -1; // 输入字符最大长度的限制,-1为不限制
    private double maxValue = 0; // 如果输入的是数字,则最大值限制
    private boolean isMaxValue = false; // 是否采用了最大值限制
    private Toolkit toolkit = null; // 用来在错误的时候发出系统声音
    public CheckInput() {
        super();
        this.init();
    }
    private void init() {
        toolkit = Toolkit.getDefaultToolkit();
    }   
    public void setCharLimit(String limit) {
        this.limit = limit;
    }
    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }
    public void setMaxValue(double maxValue){
        this.isMaxValue = true;
        this.maxValue = maxValue;
    }
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException, NumberFormatException {
        //offs起始的偏移量  str - 要插入的字符串
        // 若字符串为空,直接返回。
        if (str == null) {
            return;
        }
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            String temp = String.valueOf(ch[i]);
            // 如果要输入的字符不在允许范围内
            boolean ab=Pattern.compile(limit).matcher(temp).find();
            if (!ab) {
               toolkit.beep(); // 发出声音
               return;
            }
            // 如果有字符长度限制,并且现在的字符长度已经大于或等于限制
            if (maxLength > -1 && this.getLength() >= maxLength) {
                toolkit.beep(); // 发出声音
                return;
            }            
        }
        // 如果内容设置了最大数字
        if (isMaxValue) {
            String s = this.getText(0, this.getLength()); // 文档中已有的字符
            s = s.substring(0, offs) + str + s.substring(offs, s.length());
            if (Double.parseDouble(s) > maxValue) {   
                toolkit.beep(); // 发出声音   
                return;
            }
        }   
        super.insertString(offs, new String(ch), a);
    }
}
----------------解决方案--------------------------------------------------------
用setDocument()方法设置一下就好了啊
----------------解决方案--------------------------------------------------------