我最近在网上看到一篇文章很不错,对于限制文本框输入长度的显示很方便

JAVA不像C#能够有maxLength这个属性对文本框的输入长度进行控制,但也是有办法实现相应的功能的。

写一个MyDocument类,继承PlainDocument。重写insertString(int offset,String str,AttributeSet a)方法。

方法如下:

package com.dao;

import javax.swing.text.BadLocationException;

import javax.swing.text.PlainDocument;

public class MyDocument extends PlainDocument {

 private int maxLength;      

public MyDocument(int newMaxLength)      {    

      super();          maxLength=newMaxLength;      

}      public MyDocument()      {      

    this(10);      }      

public void insertString(int offset,String str,javax.swing.text.AttributeSet a) throws BadLocationException      {      

    if(getLength()+str.length()>maxLength)          {              return;          }       

   else          {              super.insertString(offset, str,a);          }      

 

 

 

如果觉得不详细,可以参考http://blog.sina.com.cn/s/blog_7750745b0101a56h.html

相关文章:

  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
  • 2021-11-05
  • 2021-10-19
  • 2022-01-07
  • 2021-12-28
  • 2021-10-26
猜你喜欢
  • 2022-01-25
  • 2021-12-08
  • 2021-10-19
  • 2022-12-23
  • 2021-12-08
  • 2022-12-23
  • 2021-12-08
相关资源
相似解决方案