JTextField的问题

cxycxy1984 2005-11-23 02:27:01
怎么可是使在JTextField输入字符控制在10个之内啊??
...全文
142 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
tomcatjava 2005-11-23
  • 打赏
  • 举报
回复
最简单的演示:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class TextFieldTest extends JFrame
{
public TextFieldTest() {
setSize( 400,400 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

JTextField text = new JTextField();
text.setDocument( new NumberDocument(text) );
getContentPane().add( text,BorderLayout.NORTH );

setVisible( true );
}

class NumberDocument extends PlainDocument
{
JTextField text = null;

NumberDocument( JTextField text ) {
this.text = text;
}

public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if( (null == str)|| ("".equals(str)) ) return;

StringBuffer sb = new StringBuffer();
sb.append( text.getText() );
sb.insert( offs,str );
try{
if( sb.length() <= 10 ){
super.insertString(offs, str, a);
}
}catch (NumberFormatException ex){}
}
}

public static void main( String args[] ) {
new TextFieldTest();
}
}

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧