java 限制 JTextField 中的输入长度不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13075564/
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
Limiting Length of Input in JTextField is not working
提问by Naruto
I am trying to limit the max length of character a user can input in a textfield but It seems to be not working.
我试图限制用户可以在文本字段中输入的最大字符长度,但它似乎不起作用。
Here is the code:
这是代码:
text2 = new JTextField("Enter text here",8);
Is there anything I am doing wrong? How can I make the limit to work properly?
有什么我做错了吗?我怎样才能使限制正常工作?
回答by Duncan Jones
You current code is not setting the maximum length, rather it is defining the number of visible columns.
您当前的代码没有设置最大长度,而是定义了可见列的数量。
To restrict the maximum length of the data, you can set a custom Document
for the text field that does not permit additions that break the maximum length restriction:
要限制数据的最大长度,您可以Document
为文本字段设置一个自定义,不允许违反最大长度限制的添加:
public final class LengthRestrictedDocument extends PlainDocument {
private final int limit;
public LengthRestrictedDocument(int limit) {
this.limit = limit;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null)
return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offs, str, a);
}
}
}
Then set your text field to use this document:
然后设置您的文本字段以使用此文档:
text2.setDocument(new LengthRestrictedDocument(8));
回答by Reimeus
The constructor
构造函数
new JTextField("Enter text here",8);
sets the number of visible columns to 8 but doesn't restrict you from entering more.
将可见列的数量设置为 8,但不限制您输入更多。
You could use a DocumentFilterto restrict the input length.
您可以使用DocumentFilter来限制输入长度。
回答by angrydad
Simply extend the JTextField Class and override the KeyReleased event in the constructor and point it on a new method that checks the length:
只需扩展 JTextField 类并覆盖构造函数中的 KeyReleased 事件并将其指向检查长度的新方法:
package gui;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class RecordClassTextField extends JTextField {
public RecordClassTextField() {
this.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
cleanText();
}
});
}
private void cleanText()
{
if(this.getText().length() > 17){
System.out.println("Over 17");
}
}
}
回答by Swapnil Nagtilak
No need to use any API
Simply write this code on TextFieldKeyTyped
event
无需使用任何API
只需在TextFieldKeyTyped
事件 上编写此代码
if (jTextField.getText().trim().length() == 8 || evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE) {
evt.consume();
}
And before using this code set JTextField
property setTransferHandler(null);
that will prevent from pasting.
在使用此代码集JTextField
属性之前setTransferHandler(null);
,将阻止粘贴。