Java界面设计之禁止特定字符输入

package test;

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 demo {
    public static void main(String[] args) {
        Frame f = new Frame("计算器");
        f.setBounds(400,  200,  400, 300);
        f.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                 System.exit(0);
             }
         });

        f.setLayout(new FlowLayout());
         Label label = new Label("请输入你的QQ号");

         TextField  tf = new TextField(40);

         f.add(label);
         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.setVisible(true);
    }
}

你可能感兴趣的:(Java)