java - Jtextfield and keylistener -


i have jtextfield (jt) want user types "e" example in it, word "example" written automatically in jtextfield.

i use code:

keylistener keylistener = new keylistener() {     public void keypressed(keyevent e) {         jt.settext("example");     } }  

but gives "examplee" when e pressed! ideas? lot

don't use keylistener on text components, there rafter of issues (not been notified, mutation exceptions, not been notified when user pastes field), instead, should using documentfilter

for example...

import java.awt.eventqueue; import java.awt.gridbaglayout; import javax.swing.jframe; import javax.swing.jtextfield; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; import javax.swing.text.abstractdocument; import javax.swing.text.attributeset; import javax.swing.text.badlocationexception; import javax.swing.text.documentfilter;  public class textfieldexample {      public static void main(string[] args) {         new textfieldexample();     }      public textfieldexample() {         eventqueue.invokelater(new runnable() {             @override             public void run() {                 try {                     uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname());                 } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) {                 }                  jtextfield field = new jtextfield(20);                 ((abstractdocument)field.getdocument()).setdocumentfilter(new exampleexpandingdocumentfilter());                  jframe frame = new jframe("testing");                 frame.setdefaultcloseoperation(jframe.exit_on_close);                 frame.setlayout(new gridbaglayout());                 frame.add(field);                 frame.pack();                 frame.setlocationrelativeto(null);                 frame.setvisible(true);             }         });     }      public class exampleexpandingdocumentfilter extends documentfilter {          @override         public void insertstring(filterbypass fb, int offset, string text, attributeset attr) throws badlocationexception {             system.out.println("i" + text);             super.insertstring(fb, offset, text, attr);         }          @override         public void replace(filterbypass fb, int offset, int length, string text, attributeset attrs) throws badlocationexception {             if ("e".equalsignorecase(text)) {                 text = "example";             }             super.replace(fb, offset, length, text, attrs);          }      }  } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -