【问题标题】:Limit character input in jtextfield or area限制 jtextfield 或区域中的字符输入
【发布时间】:2013-10-05 13:32:04
【问题描述】:

我正在尝试限制多个 jtextfield 上的字符输入。这两个字段有不同的字符限制,同时它们不能接受空白作为他们的第一个字符......例如,第一个字段只有 5 个字符限制,然后第二个字段有 10 个字符限制..我被困在这个问题上这是我正在使用的代码:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

 public class Restriction {

    public Restriction() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Restriction();
            }
        });
    }

    private void initComponents() {
        GridBagConstraints Cons = new GridBagConstraints();
        JFrame frame = new JFrame();
        JPanel panel = new JPanel(new GridBagLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField jtf = new JTextField(20);
        JTextField jtf2 = new JTextField(20);
        //add filter to document
        ((AbstractDocument) jtf.getDocument()).setDocumentFilter(new MyDocumentFilter());
        MyDocumentFilter.charLimit(5);
        ((AbstractDocument) jtf2.getDocument()).setDocumentFilter(new MyDocumentFilter());
        MyDocumentFilter.charLimit(10);
        Cons.gridy = 0;
        panel.add(jtf, Cons);
        Cons.gridy = 1;
        panel.add(jtf2,Cons);  
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

class MyDocumentFilter extends DocumentFilter {

    static int Limit;

    public static void charLimit(int Limitation){
        Limit = Limitation;
    }

    @Override
    public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
        //we want standard behavior if we are not placing space at start of JTextField
        //or if we are placing text at start of JTextField but first character is not whitespace
        if ( i!=0 && i< Limit || ( i==0 && !Character.isWhitespace(string.charAt(0)) ) ){
            super.replace(fb, i, i1, string, as);
        }else{
            System.out.println("no spaces allowed");
        }
    }

    @Override
    public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
        super.remove(fb, i, i1);
    }

    @Override
    public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
        super.insertString(fb, i, string, as);

    }
}

【问题讨论】:

    标签: java swing jtextfield documentfilter


    【解决方案1】:

    我会使用javax.swing.text.Document

    您可以像这样启动它:

     public static Document createTextDocument(int maxLength){
            return new TextDocument(maxLength);
        }
    
    ...
    
    Document document = createTextDocument(5); // limit to 5 chars
    textField1.setDocument(document);
    
    document = createTextDocument(10); // limit to 10 chars
    textField2.setDocument(document);
    

    这里是自定义TextDocument 类:

    public class TextDocument extends PlainDocument{
    
    
        private static final long serialVersionUID = 1L;
        private int maxLength = Integer.MAX_VALUE;
    
        TextDocument(){}
        TextDocument(int maxlength){this.maxLength=maxlength;}
    
         public void setMaxLength(int maxLength) {
                if (maxLength < 0)
                    throw new IllegalArgumentException("maxLength<0");
                this.maxLength = maxLength;
            }
    
         public void insertString(int offset, String str, AttributeSet attr)
         throws BadLocationException {
             if (validateLength(offset, str) == false)
                    return;
    
                super.insertString(offset, str, attr);
         }
    
         private boolean validateLength(int offset, String toAdd) {
                String str_temp;
                //String str_text = "";
                String str1 = "";
                String str2 = "";
                try {
                    str1 = getText(0, offset);
                    str2 = getText(offset, getLength() - offset);
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                str_temp = str1 + toAdd + str2;
                if (maxLength < str_temp.length()) {
                    beep();
                    return false;
                } else
                    return true;
    
            }
    
            private void beep() {
                java.awt.Toolkit.getDefaultToolkit().beep();
            }
    }
    

    希望对你有帮助

    【讨论】:

    • 感谢您的回复.. 但我的问题仍然存在我正在尝试使用不同的字符限制来限制 2 个 Jtextfield,但同时它不接受空格作为其第一个字符
    • 看我的例子,你用TextDocument只提供5和10
    • 关于开头的空白,只需在validateLength方法中更改我的课程。很简单
    • 我刚刚想通了..我只是将我的代码的条件添加到您的代码中...对不起,谢谢,因为我还不熟悉过滤和限制..
    • 不要使用自定义文档,请使用您上次发帖中已经建议的 DocumentFilter。 API 随着时间的推移而发展,您可以在使用 DocumentFilters 时创建更多可重用的代码。
    【解决方案2】:

    您可以通过覆盖每个 JTextField 的 keyTyped 事件来避免使用 Document 的复杂性:

    txtGuess = new JTextField();
    txtGuess.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) { 
            if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
                e.consume(); 
        }  
    });
    

    这会将猜谜游戏文本字段中的字符数限制为 3 个字符,方法是覆盖 keyTyped 事件并检查文本字段是否已经有 3 个字符 - 如果是,您正在“消耗”键事件(e ) 这样它就不会像平常一样被处理。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2022-10-21
      • 1970-01-01
      • 2014-10-14
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2014-01-25
      相关资源
      最近更新 更多