我想设置JTextField
的最大长度,这样就不能输入超过限制的字符数了。这是我到目前为止的代码......
textField = new JTextField();
textField.setBounds(40, 39, 105, 20);
contentPane.add(textField);
textField.setColumns(10);
有没有简单的方法来限制字符数?
答案 0 :(得分:29)
您可以执行以下操作(取自here):
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);
}
}
编辑:看一下之前的this SO帖子。您可以截取按键事件,并根据文本字段中的当前字符数添加/忽略它们。
答案 1 :(得分:18)
自Java 1.4中引入DocumentFilter
以来,覆盖Document
的需求已被减少。
DocumentFilter
提供了过滤内容在实际到达之前传递给Document
的方法。
这些允许字段继续维护所需的文档,同时提供过滤用户输入的方法。
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);
}
}
}
}
答案 2 :(得分:3)
Swing工具包并不包含此功能,这很奇怪,但这是您问题的最佳答案:
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课程中使用这个有趣的猜谜游戏示例&#34;像孩子一样学习Java&#34;。 干杯 - 布赖森
答案 3 :(得分:0)
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
{
if(jTextField1.getText().length()>=5)
{
jTextField1.setText(jTextField1.getText().substring(0, 4));
}
}
我已经使用了一个名为jTextField1的jtextfield,代码位于其按下键的事件中。我测试了它,它的工作原理。我正在使用NetBeans IDE。
答案 4 :(得分:0)
private void validateInput() {
if (filenametextfield.getText().length() <= 3 )
{
errorMsg2.setForeground(Color.RED);
}
else if(filenametextfield.getText().length() >= 3 && filenametextfield.getText().length()<= 25)
{
errorMsg2.setForeground(frame.getBackground());
errorMsg.setForeground(frame2.getBackground());
}
else if(filenametextfield.getText().length() >= 25)
{
remove(errorMsg2);
errorMsg.setForeground(Color.RED);
filenametextfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if(filenametextfield.getText().length()>=25)
{
e.consume();
e.getModifiers();
}
}
});
}
}
答案 5 :(得分:0)
这是另一种限制长度的方法,如下所示。
label_4_textField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent arg0) {
if(label_4_textField.getText().length()>=4) // Limit to 4 characters
{
label_4_textField.setText(label_4_textField.getText().substring(0,3));
}
}
});
答案 6 :(得分:-1)
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
if (jTextField1.getText().length()>=3) {
getToolkit().beep();
evt.consume();
}
}
&#13;
答案 7 :(得分:-1)
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();
}
}
});
}
答案 8 :(得分:-1)
以下是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);