i want take letters input in name field.
i have tried using matches method unfortunately wrong , exception being thrown.
is there other method of checking same?
import java.awt.borderlayout; import java.awt.flowlayout; import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import java.awt.gridlayout; import java.awt.insets; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.*; public class createaccount extends jframe implements actionlistener{ jpanel details = new jpanel(new gridbaglayout()); jlabel fname= new jlabel("first name:"); jtextfield firstnamefield = new jtextfield(10); jlabel lname= new jlabel("last name:"); jtextfield lastnamefield = new jtextfield(10); jlabel initialdeposit = new jlabel("initial deposit: "); jtextfield initialdepositfield = new jtextfield(10); string accounttypes[] = {"savings","current"}; jcombobox accounttypescombobox = new jcombobox(accounttypes); jlabel accounttype= new jlabel("account type: "); jbutton submit = new jbutton("submit"); jbutton review = new jbutton("review"); administrator admin = new administrator(); user u[] = new user[admin.maxnumberofusers]; createaccount() { buildgui(); setsize(400,300); setlocationrelativeto(null); setdefaultcloseoperation(jframe.exit_on_close); } public void initialiseusercount() { admin.numberofsavingsaccount = 0; admin.numberofcurrentaccount = 0; admin.numberofusers=0; } public void buildgui() { settitle("new account form"); //jpanel submitpanel = new jpanel(); //submitpanel.add(submit); gridbagconstraints c = new gridbagconstraints(); c.insets=new insets(10,10,10,10); // stretch components horizontally (but not vertically) c.fill = gridbagconstraints.horizontal; // components short or narrow space // should pinned northwest (upper left) corner c.anchor = gridbagconstraints.northwest; // give "last" component space possible c.weightx = 1.0; c.gridx=0; c.gridy=0; details.add(fname,c); c.gridx=1; c.gridy=0; details.add(firstnamefield,c); c.gridx=0; c.gridy=1; details.add(lname,c); c.gridx=1; c.gridy=1; details.add(lastnamefield,c); c.gridx=0; c.gridy=2; details.add(initialdeposit,c); c.gridx=1; c.gridy=2; details.add(initialdepositfield,c); c.gridx=0; c.gridy=3; details.add(accounttype,c); c.gridx=1; c.gridy=3; details.add(accounttypescombobox,c); c.gridx=0; c.gridy=4; details.add(submit,c); c.gridx=1; c.gridy=4; details.add(review,c); add(details); firstnamefield.addactionlistener(this); review.addactionlistener(this); } public void actionperformed(actionevent e) { if(e.getsource()==firstnamefield) { try { string ufname = firstnamefield.gettext().tostring(); if(!ufname.matches("[a-za-z]+")) throw new exception(); } catch(exception e1) { firstnamefield.settext(""); joptionpane.showmessagedialog(firstnamefield,"please enter valid name!"); } } } }
you can try use regex
if(!ufname.matches("^[a-za-z]+$"))