http://www.rgagnon.com/javadetails/java-0198.htmlimport javax.swing.text.Plaindocument;import javax.swing.text.AttributeSet;import javax.swing.text.BadLocationException;public class JTextFieldLimit extends Plaindocument { private int limit; JTextFieldLimit(int limit) { 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); } }}
然后
import java.awt.*;import javax.swing.*; public class DemoJTextFieldWithLimit extends JApplet{ JTextField textfield1; JLabel label1; public void init() { getContentPane().setLayout(new FlowLayout()); // label1 = new JLabel("max 10 chars"); textfield1 = new JTextField(15); getContentPane().add(label1); getContentPane().add(textfield1); textfield1.setdocument (new JTextFieldLimit(10)); }}
(谷歌的第一个结果)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)