In an enterprise application when there is huge amount data in a table
users feel comfortable if you provide them a option for filtering the
table. Here I show you an example of how to filter a JTable row with
input in a JTextField.
Declare a JTable and your own table model
private MyTableModel tableModel;
private javax.swing.JTable jtblSampleTable;
Now declare a table row sorter for that table model
private TableRowSortersorter ;
//
Initialize all the above three declared variables
jtblSampleTable = new javax.swing.JTable();
tableModel = new MyTableModel();
sorter = new TableRowSorter(tableModel);
//
Bind the model with the table
jtblSampleTable.setModel(tableModel);
Set the sorter as the row sorter for the table
jtblSampleTable.setRowSorter(sorter);
Now declare a JTextField
jtfSearch = new javax.swing.JTextField();
Add a document listener for the search text field.
jtfSearch.getDocument().addDocumentListener(
new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
newFilter();
}
public void insertUpdate(DocumentEvent e)
{
newFilter();
}
public void removeUpdate(DocumentEvent e)
{
newFilter();
}
}
);
Here is the newFilter method
private void newFilter()
{
RowFilter< MyTableModel , Object> rf = null;
//declare a row filter for your table model
Try
{
rf = RowFilter.regexFilter("^" + jtfSearch.getText(), 0);
//initialize with a regular expression
}
catch (java.util.regex.PatternSyntaxException e)
{
return;
}
sorter.setRowFilter(rf);
}
The above example is able to filter JTable for its first column.