Limiting TextField inputs

蹲街弑〆低调 提交于 2019-12-09 01:24:38

问题


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

 private void jTextField5KeyTyped(java.awt.event.KeyEvent evt) {                                     
//This limits the input:
 if(jTextField5.getText().length()>=2) {
    jTextField5.setText(jTextField5.getText().substring(0, 1));
}
}                  

It successfully limits the input. However, when I tried to press other characters on the keyboard, it changes the last character on the textfield. Any ideas to stop this? I know others will say that I should use Document(Can't remember) in making this kind of stuff, but I can't. I don't know how to do it in netbeans. Please help.


回答1:


Here's a simple way to do it:

private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {                       
 if(textField.getText().length()>=2) {  
   evt.consume();
 }
}



回答2:


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


}


来源:https://stackoverflow.com/questions/21572407/limiting-textfield-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!