I have a JTable
populated with data from a database. I have added a search function that display the rows, if word matched to some rows when the data is typed into a JTextField
. But at the minute as you type a string or word that do not matches any of the rows data, what I want to do is to hide all the rows, and the JTable
will show just the column names. Just like when something matches IT, shows those rows only which has the string that user typed and hide others.
Here is my code that I am using:
if (text.length() == 0) {
sorter.setRowFilter(null);
} else {
try {
sorter.setRowFilter(
RowFilter.regexFilter(text));
} catch (PatternSyntaxException pse) {
System.err.println("Bad regex pattern");
}
}
}
You want to use a
DocumentListener
, along with the row filter. You can see how to Write a DocumentListener.Basically the listener listens for changes in the underlying document of the text field. From the methods you override in the
DocumentListener
, you can get the text, like you're currently doing, and set the regex ex filter like you're currently doingHere's simple example (disregard the applet. I just got the boilerplate code from this post and added the document listener). Note: that same post has an answer provided that will allow you to filter in a case-insensitive way, if you're looking for that functionality