请问如何限制jTextFiled的输入字符的长度? 据我所知,没有现成的方法,自己写制约函数吧,在keyPress中加一些check. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 jTextField.setDocument( doc)Document里做,看看PlainDocument就明白了. import com.sun.java.swing.text.*;//import javax.swing.text.*;public class JTextFieldLimit extends PlainDocument { private int limit; // optional uppercase conversion private boolean toUppercase = false; JTextFieldLimit(int limit) { super(); this.limit = limit; } JTextFieldLimit(int limit, boolean upper) { super(); this.limit = limit; toUppercase = upper; } public void insertString (int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) return; if ((getLength() + str.length()) <= limit) { if (toUppercase) str = str.toUpperCase(); super.insertString(offset, str, attr); } }} import java.awt.*; import com.sun.java.swing.*; //import javax.swing.*; public class tswing 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)); } } 在线坐等、、关于文件读写、、 这段代码为什么会报空指针异常 学习方法请教 for语句中的一个冒号什么意思 JAVA方法里面定义内部类改如何访问? 多线程访问静态变量 只获得值 不做改变变量操作 是否需要同步 安装问题,不难?即答即结! 未报告的异常错误IOException 求助我想好好学习java,该选择那本书? tomcat提供连接池吗? 美国2001年IT职位需求TOP10 jvm探讨
Document里做,看看PlainDocument就明白了.
//import javax.swing.text.*;
public class JTextFieldLimit extends PlainDocument {
private int limit;
// optional uppercase conversion
private boolean toUppercase = false;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
toUppercase = upper;
}
public void insertString
(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) return; if ((getLength() + str.length()) <= limit) {
if (toUppercase) str = str.toUpperCase();
super.insertString(offset, str, attr);
}
}
}
import java.awt.*;
import com.sun.java.swing.*;
//import javax.swing.*; public class tswing 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));
}
}