如何限制JTextField中的字符数?

如何限制在JTextField中input的字符数?

假设我想input最多5个字符。 之后,不能input字符。

http://www.rgagnon.com/javadetails/java-0198.html

 import javax.swing.text.PlainDocument 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); } } } 

然后

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

(谷歌的第一个结果)

如果你想把所有的东西都放到一块代码中,那么你可以把Tim的答案和在JTextField的API上find的例子的方法混合起来,你会得到这样的东西:

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

然后,由于JTextFieldLimit已经具有内部的function,因此不需要将文档添加到JTextFieldLimit。

很好的问题,而奇怪的是,Swing工具包本身并没有为JTextFields包含这个function。 但是,我的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(); } }); 

这将猜测游戏文本字段中的字符数限制为3个字符,方法是重写keyTyped事件并检查文本字段是否已经有3个字符 – 如果是,则“消耗”关键事件(e)它不会像正常一样得到处理。

请阅读Swing教程中有关实现DocumentFilter的部分以获得更新的解决scheme。

此解决scheme将工作任何文档,而不仅仅是一个PlainDocument。

这是比接受的更新的解决scheme。

试试这个:

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

我已经通过使用下面的代码段解决了这个问题:

 private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { boolean max = jTextField1.getText().length() > 4; if ( max ){ evt.consume(); } } 
 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(); } } } }