1. First, let's look at my needs, as follows:
control text box can only enter numeric characters
2. Source code:
Packagecn.itcast_07;Importjava.awt.FlowLayout;ImportJava.awt.Frame;ImportJava.awt.Label;ImportJava.awt.TextField;ImportJava.awt.event.KeyAdapter;Importjava.awt.event.KeyEvent;ImportJava.awt.event.WindowAdapter;Importjava.awt.event.WindowEvent;/** If you enter a non-numeric character, the effect of your keyboard entry will be canceled. */ Public classFramedemo { Public Static voidMain (string[] args) {//Create a Form object and set propertiesFrame f =NewFrame ("Cannot enter non-numeric characters"); F.setbounds (400, 200, 400, 300); F.setlayout (NewFlowLayout ()); //Create a label label ObjectLabel label =NewLabel ("Please enter your QQ number, can not be a non-digital, do not believe you try"); TextField TF=NewTextField (40); //Add to formf.add (label); F.add (TF); //set the form to closeF.addwindowlistener (NewWindowadapter () {@Override Public voidwindowclosing (windowevent e) {system.exit (0); } }); //add an event to a text boxTf.addkeylistener (NewKeyadapter () {@Override Public voidkeypressed (KeyEvent e) {//If you get a character that is not a numeric character, cancel the event//idea: First get character, judge character, cancel event//Char Getkeychar () CharCH =E.getkeychar ();//System.out.println (CH); if(! (ch>= ' 0 ' && ch<= ' 9 ') ) {e.consume (); } } }); //Set Form VisibleF.setvisible (true); }}
From for notes (Wiz)
GUI Programming Note (Java) 09:gui control text box can only enter numeric character cases