Java 限制 TextField 输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21572407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:26:10  来源:igfitidea点击:

Limiting TextField inputs

javanetbeansjtextfield

提问by user3260589

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.

它成功地限制了输入。但是,当我尝试按键盘上的其他字符时,它会更改文本字段上的最后一个字符。有什么想法可以阻止这种情况吗?我知道其他人会说我应该使用 Document(不记得)来制作这种东西,但我不能。我不知道如何在 netbeans 中做到这一点。请帮忙。

采纳答案by A-SM

Here's a simple way to do it:

这是一个简单的方法:

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

回答by Alya'a Gamal

Try this Example which Use PlainDocument:

试试这个使用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);
}


}