限制JTextField中的字符数

我想设置一个JTextField的最大长度,所以你不能input比限制更多的字符。 这是我到目前为止的代码…

  textField = new JTextField(); textField.setBounds(40, 39, 105, 20); contentPane.add(textField); textField.setColumns(10); 

有没有简单的方法来限制字符数量?

你可以做这样的事情(从这里拿):

 import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.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(15); add(label1); add(textfield1); textfield1.setDocument(new JTextFieldLimit(10)); setSize(300,300); setVisible(true); } } 

编辑:看看这个以前的SOpost。 您可以拦截按键事件,并根据文本字段中的当前字符数量添加/忽略它们。

自从在Java 1.4中引入DocumentFilter以来,就不再需要重写Document了。

DocumentFilter提供了在实际到达之前过滤传递给Document内容的方法。

这些允许该字段继续保持所需的文档,同时提供过滤来自用户的input的手段。

 import java.awt.EventQueue; import java.awt.GridBagLayout; import javax.swing.JFrame; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; public class LimitTextField { public static void main(String[] args) { new LimitTextField(); } public LimitTextField() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JTextField pfPassword = new JTextField(20); ((AbstractDocument)pfPassword.getDocument()).setDocumentFilter(new LimitDocumentFilter(15)); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridBagLayout()); frame.add(pfPassword); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class LimitDocumentFilter extends DocumentFilter { private int limit; public LimitDocumentFilter(int limit) { if (limit <= 0) { throw new IllegalArgumentException("Limit can not be <= 0"); } this.limit = limit; } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { int currentLength = fb.getDocument().getLength(); int overLimit = (currentLength + text.length()) - limit - length; if (overLimit > 0) { text = text.substring(0, text.length() - overLimit); } if (text.length() > 0) { super.replace(fb, offset, length, text, attrs); } } } } 
 private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) { if(jTextField1.getText().length()>=5) { jTextField1.setText(jTextField1.getText().substring(0, 4)); } } 

我已经采取了jtextfield的名字是jTextField1,代码是在其按键事件。 我已经testing过,它工作。 我正在使用NetBeans IDE。

Swing工具包不包括这个function是奇怪的,但是这里是对你的问题的最好的答案:

  textField = new JTextField(); textField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if (txtGuess.getText().length() >= 3 ) // limit to 3 characters e.consume(); } }); 

我在我的Udemy.com课程“Learn Java Like a Kid”中使用这个有趣的猜谜游戏例子。 干杯 – 布赖森

 private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { if (jTextField1.getText().length()>=3) { getToolkit().beep(); evt.consume(); } } 
 public void Letters(JTextField a) { a.addKeyListener(new KeyAdapter() { @Override public void keyTyped(java.awt.event.KeyEvent e) { char c = e.getKeyChar(); if (Character.isDigit(c)) { e.consume(); } if (Character.isLetter(c)) { e.setKeyChar(Character.toUpperCase(c)); } } }); } public void Numbers(JTextField a) { a.addKeyListener(new KeyAdapter() { @Override public void keyTyped(java.awt.event.KeyEvent e) { char c = e.getKeyChar(); if (!Character.isDigit(c)) { e.consume(); } } }); } public void Caracters(final JTextField a, final int lim) { a.addKeyListener(new KeyAdapter() { @Override public void keyTyped(java.awt.event.KeyEvent ke) { if (a.getText().length() == lim) { ke.consume(); } } }); } 

这里是npinti的答案的优化版本:

 import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.PlainDocument; import java.awt.*; public class TextComponentLimit extends PlainDocument { private int charactersLimit; private TextComponentLimit(int charactersLimit) { this.charactersLimit = charactersLimit; } @Override public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException { if (isAllowed(input)) { super.insertString(offset, input, attributeSet); } else { Toolkit.getDefaultToolkit().beep(); } } private boolean isAllowed(String string) { return (getLength() + string.length()) <= charactersLimit; } public static void addTo(JTextComponent textComponent, int charactersLimit) { TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit); textComponent.setDocument(textFieldLimit); } } 

要为您的JTextComponent添加限制,只需编写以下代码行:

 JTextFieldLimit.addTo(myTextField, myMaximumLength);