java - JTextField set input limit -
hi trying use setdocument method limit number of characters user can input in text field. somehow not limit no of input characters. here's code
import javax.swing.text.attributeset; import javax.swing.text.badlocationexception; import javax.swing.text.plaindocument; public class jtextfieldcharlimit extends plaindocument { private int limit; public jtextfieldcharlimit(int limit) { super(); this.limit = limit; } public void inserstring(int offset, string str, attributeset set) throws badlocationexception { if(str == null) { return; } else if((getlength() + str.length()) <= limit) { str = str.touppercase(); super.insertstring(offset, str, set); } } }
i using class in class have declared text field follows:
void playerinfoscreen(jframe mainframe, jpanel menupanel) { final screenconstructor playername = new screenconstructor(); final jframe frame = mainframe; final jpanel returnpanel = menupanel; final jpanel panel = playername.createpanel("menu panel"); final jbutton returnbutton = playername.createbutton("main menu"); final jtextfield textentry = playername.createtextfield(10); // text field length needs set prevent long texts final jlabel label = playername.createlabel("enter player name:"); playername.addbuttontopanel(panel, returnbutton); playername.addlabeltopanel(panel, label); playername.addjtextfieldtopanel(panel, textentry); textentry.setdocument(new jtextfieldcharlimit(5)); playername.displayscreen(frame, panel); // check esc button let user return main menu textentry.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { string player = textentry.gettext(); // save entered player name storedplayername = player; // store player in order use in highscores , display on game screen gamescreen game = new gamescreen(frame, panel); // go game screen } }); returnbutton.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { frame.setcontentpane(returnpanel); // go previous panel } }); }
use documentfilter
. see implementing document filter , documentfilter examples more details.
public class sizefilter extends documentfilter { private int maxcharacters; public sizefilter(int maxchars) { maxcharacters = maxchars; } public void insertstring(filterbypass fb, int offs, string str, attributeset a) throws badlocationexception { if ((fb.getdocument().getlength() + str.length()) <= maxcharacters) super.insertstring(fb, offs, str, a); else toolkit.getdefaulttoolkit().beep(); } public void replace(filterbypass fb, int offs, int length, string str, attributeset a) throws badlocationexception { if ((fb.getdocument().getlength() + str.length() - length) <= maxcharacters) super.replace(fb, offs, length, str, a); else toolkit.getdefaulttoolkit().beep(); } }
credit mdp
((abstractdocument)textentry.getdocument()).setdocumentfilter(new sizefilter(5));
Comments
Post a Comment