java - JTable filtering by an exact match to a String -
i want filter jtable
string. filter this:
pattern.quote(textfield.gettext());
but, when filter on "g" lines of jtable
entry "kg". want rows entry "g". looked @ how use tables: sorting , filtering, still don't see how.
another example: rowfilter#regexfilter(...) (java platform se 8)
the returned filter uses matcher.find() test inclusion. test exact matches use characters '^' , '$' match beginning , end of string respectively. example, "^foo$" includes rows string "foo" , not, example, "food". see pattern complete description of supported regular-expression constructs.
import java.awt.*; import java.awt.event.*; import java.util.regex.*; import javax.swing.*; import javax.swing.table.*; public class jtablefilterdemo2 { public jcomponent makeui() { string[] columnnames = {"item"}; object[][] data = {{"g"}, {"kg"}, {"xg"}, {"y"}, {"z"}, {"*g"}}; defaulttablemodel model = new defaulttablemodel(data, columnnames); tablerowsorter<tablemodel> sorter = new tablerowsorter<>(model); jtable table = new jtable(model); table.setrowsorter(sorter); jtextfield textfield = new jtextfield("g"); jbutton button = new jbutton("toggle filter"); button.addactionlistener(e -> { if (sorter.getrowfilter() != null) { sorter.setrowfilter(null); } else { string text = pattern.quote(textfield.gettext()); string regex = string.format("^%s$", text); sorter.setrowfilter(rowfilter.regexfilter(regex)); } }); jpanel p = new jpanel(new borderlayout()); p.add(textfield, borderlayout.north); p.add(new jscrollpane(table)); p.add(button, borderlayout.south); return p; } public static void main(string[] args) { eventqueue.invokelater(() -> { jframe f = new jframe(); f.setdefaultcloseoperation(windowconstants.exit_on_close); f.getcontentpane().add(new jtablefilterdemo2().makeui()); f.setsize(320, 240); f.setlocationrelativeto(null); f.setvisible(true); }); } }
Comments
Post a Comment