方法:
键盘输入以后采用的方法:
按下某个键时调用此方法:KeyPressed(KeyEvent e )
使用此事件,以便不会按照默认的方式处理事件:public void consume()
代码
package cn.idcast2; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.TextField; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class FrameDemo3 { public static void main(String[] args) { Frame f = new Frame("QQ号码信息"); f.setBounds(400, 200, 400, 300); f.setLayout(new FlowLayout()); // 这里表示的标签,即注释 Label l = new Label("只能输入数字"); TextField tf = new TextField(40); f.add(l); f.add(tf); // 判断键盘录入以后的数据是否满足条件 tf.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { char ch = e.getKeyChar(); if (!(ch >= ‘0‘ && ch <= ‘9‘)) { e.consume(); } } }); f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub System.exit(0); } }); f.setVisible(true); } }
结果显示:
时间: 2024-10-21 23:49:32