限制 JTextField 中的字符数 [英] Limiting the number of characters in a JTextField

查看:33
本文介绍了限制 JTextField 中的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个JTextField的最大长度,这样你就不能输入超过限制的字符了.这是我到目前为止的代码...

I want to set the maximum length of a JTextField, so that you can't enter more characters than the limit. This is the code I have so far...

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

有没有什么简单的方法可以限制字符数?

Is there any simple way to put a limit on the number of characters?

推荐答案

你可以这样做(取自 此处):

You can do something like this (taken from 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);
  }
}

看看这个以前的SO邮政.您可以拦截按键事件并根据文本字段中的当前字符数添加/忽略它们.

Take a look at this previous SO post. You could intercept key press events and add/ignore them according to the current amount of characters in the textfield.

这篇关于限制 JTextField 中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆