Java 如何限制 JTextField 中的字符数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3519151/
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
How To limit the number of characters in JTextField?
提问by Santosh V M
How to limit the number of characters entered in a JTextField?
如何限制在 JTextField 中输入的字符数?
Suppose I want to enter say 5 characters max. After that no characters can be entered into it.
假设我想输入最多 5 个字符。之后就不能再输入字符了。
采纳答案by tim_yates
http://www.rgagnon.com/javadetails/java-0198.html
http://www.rgagnon.com/javadetails/java-0198.html
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
public class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
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);
}
}
}
Then
然后
import java.awt.*;
import javax.swing.*;
public class DemoJTextFieldWithLimit extends JApplet{
JTextField textfield1;
JLabel label1;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
getContentPane().add(label1);
getContentPane().add(textfield1);
textfield1.setDocument
(new JTextFieldLimit(10));
}
}
(first result from google)
(来自谷歌的第一个结果)
回答by Francisco J. Güemes Sevilla
If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:
如果您想将所有内容都包含在一段代码中,那么您可以将 tim 的答案与在JTextField的 API 上找到的示例方法混合,您将得到如下内容:
public class JTextFieldLimit extends JTextField {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
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);
}
}
}
}
Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.
由于 JTextFieldLimit 内部已经具备该功能,因此无需向 JTextFieldLimit 添加文档。
回答by camickr
Read the section from the Swing tutorial on Implementing a DocumentFilterfor a more current solution.
阅读 Swing 教程中关于实现 DocumentFilter 的部分,以获取更当前的解决方案。
This solution will work an any Document, not just a PlainDocument.
此解决方案适用于任何文档,而不仅仅是普通文档。
This is a more current solution than the one accepted.
这是一种比公认的更现代的解决方案。
回答by Adham Gamal
Just Try This :
试试这个:
textfield.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
getToolkit().beep();
evt.consume();
}
}
});
回答by Igor Vukovi?
import java.awt.KeyboardFocusManager;
import javax.swing.InputVerifier;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
/**
*
* @author Igor
*/
public class CustomLengthTextField extends JTextField {
protected boolean upper = false;
protected int maxlength = 0;
public CustomLengthTextField() {
this(-1);
}
public CustomLengthTextField(int length, boolean upper) {
this(length, upper, null);
}
public CustomLengthTextField(int length, InputVerifier inpVer) {
this(length, false, inpVer);
}
/**
*
* @param length - maksimalan length
* @param upper - turn it to upercase
* @param inpVer - InputVerifier
*/
public CustomLengthTextField(int length, boolean upper, InputVerifier inpVer) {
super();
this.maxlength = length;
this.upper = upper;
if (length > 0) {
AbstractDocument doc = (AbstractDocument) getDocument();
doc.setDocumentFilter(new DocumentSizeFilter());
}
setInputVerifier(inpVer);
}
public CustomLengthTextField(int length) {
this(length, false);
}
public void setMaxLength(int length) {
this.maxlength = length;
}
class DocumentSizeFilter extends DocumentFilter {
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
throws BadLocationException {
//This rejects the entire insertion if it would make
//the contents too long. Another option would be
//to truncate the inserted string so the contents
//would be exactly maxCharacters in length.
if ((fb.getDocument().getLength() + str.length()) <= maxlength) {
super.insertString(fb, offs, str, a);
}
}
public void replace(FilterBypass fb, int offs,
int length,
String str, AttributeSet a)
throws BadLocationException {
if (upper) {
str = str.toUpperCase();
}
//This rejects the entire replacement if it would make
//the contents too long. Another option would be
//to truncate the replacement string so the contents
//would be exactly maxCharacters in length.
int charLength = fb.getDocument().getLength() + str.length() - length;
if (charLength <= maxlength) {
super.replace(fb, offs, length, str, a);
if (charLength == maxlength) {
focusNextComponent();
}
} else {
focusNextComponent();
}
}
private void focusNextComponent() {
if (CustomLengthTextField.this == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
}
}
}
回答by Dr. Bryson Payne
Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. But, here's a great answer from my Udemy.com course "Learn Java Like a Kid":
很好的问题,奇怪的是 Swing 工具包本身没有为 JTextFields 包含此功能。但是,这是我的 Udemy.com 课程“像孩子一样学习 Java”中的一个很好的答案:
txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
e.consume();
}
});
This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.
这将猜谜游戏文本字段中的字符数限制为 3 个字符,方法是覆盖 keyTyped 事件并检查文本字段是否已经有 3 个字符 - 如果是,则您正在“消耗”关键事件 (e) 以便它不会像往常一样被处理。
回答by necheervan abdullah
I have solved this problem by using the following code segment:
我通过使用以下代码段解决了这个问题:
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
boolean max = jTextField1.getText().length() > 4;
if ( max ){
evt.consume();
}
}
回答by Ricardo Almeida
Just put this code in KeyTyped event:
只需将此代码放在 KeyTyped 事件中:
if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
evt.consume();
}
Where "20" is the maximum number of characters that you want.
其中“20”是您想要的最大字符数。