Limiting TextField inputs

前端 未结 2 854
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 04:04

I\'m trying to make a textfield that limits a user input. I have this code:

 private void jTextField5KeyTyped(java.awt.event.KeyEvent evt) {                          


        
相关标签:
2条回答
  • 2021-01-07 04:40

    Try this Example which Use PlainDocument :

    class JTextFieldLimit extends PlainDocument {
    
    private int limit;
    
    JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }
    
    JTextFieldLimit(int limit, boolean upper) {
        super();
        this.limit = limit;
    }
    
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }
    
        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        }
    }
    }
    
    public class Main extends JFrame {
    
    JTextField textfield1;
    JLabel label1;
    
    public void init() {
        setLayout(new FlowLayout());
        label1 = new JLabel("max 10 chars");
        textfield1 = new JTextField(10);
        add(label1);
        add(textfield1);
        textfield1.setDocument(new JTextFieldLimit(110));///enter here the Maximum input length you want
        setSize(300, 300);
        setVisible(true);
    }
    
    
    }
    
    0 讨论(0)
  • 2021-01-07 05:04

    Here's a simple way to do it:

    private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {                       
     if(textField.getText().length()>=2) {  
       evt.consume();
     }
    }
    
    0 讨论(0)
提交回复
热议问题