java - Why does the DocumentFilter not give the intended result? -
i figure must simple mistake in code or misunderstanding on part, cannot documentfilter
detect insertstring
events. below simple filter upper case letters, not important fact insertstring(..)
method never seems called!
why insertstring(..)
method of documentfilter
not called?
the filter applied jtextfield
@ top. every time insertstring(..)
called, should append information jtextarea
in center
. @ moment, there no action in text field causes text appended text area.
import java.awt.*; import javax.swing.*; import javax.swing.border.emptyborder; import javax.swing.text.*; public class filteruppercaseletters { private jcomponent ui = null; private final jtextfield textfield = new jtextfield(25); private final jtextarea textarea = new jtextarea(5, 20); filteruppercaseletters() { initui(); } public void initui() { // document filter seems nothing. documentfilter capsfilter = new documentfilter() { @override public void insertstring( documentfilter.filterbypass fb, int offset, string string, attributeset attr) throws badlocationexception { textarea.append("insertstring! " + string + "\n"); if (!string.touppercase().equals(string)) { textarea.append("insert!\n"); super.insertstring(fb, offset, string, attr); } else { textarea.append("don't insert!\n"); } } }; abstractdocument abstractdocument = (abstractdocument) textfield.getdocument(); abstractdocument.setdocumentfilter(capsfilter); ui = new jpanel(new borderlayout(4, 4)); ui.setborder(new emptyborder(4, 4, 4, 4)); ui.add(textfield, borderlayout.page_start); ui.add(new jscrollpane(textarea), borderlayout.center); } public jcomponent getui() { return ui; } public static void main(string[] args) { runnable r = new runnable() { @override public void run() { filteruppercaseletters o = new filteruppercaseletters(); jframe f = new jframe(o.getclass().getsimplename()); f.setdefaultcloseoperation(jframe.dispose_on_close); f.setlocationbyplatform(true); f.setcontentpane(o.getui()); f.pack(); f.setminimumsize(f.getsize()); f.setvisible(true); } }; swingutilities.invokelater(r); } }
the text components use replaceselection(...)
method in turn invoke replace(...)
method of abstractdocument
invoke replace(...)
method of documentfilter
.
the insertstring(...)
method called when use document.insertstring(...)
method directly update document
.
so in reality need override both methods make sure upper case conversion done.
Comments
Post a Comment