java JTextField输入字数监听
1个回答
展开全部
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.Serializable;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TextTest extends JFrame implements Serializable {
private static final long serialVersionUID=1L;
private JTextField jtf;
private JLabel jab;
TextTest(){
this.setBounds(300,300,300,200);
this.setTitle("文本测试");
this.setResizable(false);
init();
this.setVisible(true);
}
public static void main(String[] args) {
new TextTest();
}
private void init() {
this.setDefaultCloseOperation(3);
jab=new JLabel("字符检测");
jtf=new JTextField(30);
myEve();
this.add(jtf,BorderLayout.NORTH);
this.add(jab,BorderLayout.SOUTH);
}
private void myEve() {
jtf.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent k) {
int x=jtf.getText().length();
if(x>2) {
k.consume();
jab.setText("警告,字数超限,禁止输入!");
}else {
jab.setText("允许输入:");
}
}
});
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询