I have a table, and I want to search/filter in it by using a JTextField
. I have the code to do that, and it is working.
Now, what I want to do is, by a JComboBox
, select for what Column I want to search and show me the entire rows with what I searched.
This is the code I got so far:
private void Filtro(String query){
DefaultTableModel modelo = (DefaultTableModel) TabelaPessoal.getModel();
TableRowSorter<DefaultTableModel> pesquisa = new TableRowSorter<DefaultTableModel>(modelo);
TabelaPessoal.setRowSorter(pesquisa);
pesquisa.setRowFilter(RowFilter.regexFilter(query));
}
private void txt_pesquisaKeyReleased(java.awt.event.KeyEvent evt) {
String query = txt_pesquisa.getText().toLowerCase();
Filtro(query);
}
How I can do that?
Try this below code
public class ColumnName {
public String columnName;
public int columnIndex;
public ColumnName( String columnName, int columnIndex ) {
this.columnName = columnName;
this.columnIndex = columnIndex;
}
public String getColumnName() {
return columnName;
public String toString() {
return columnName;
}
public int getColumnIndex() {
return columnIndex;
}
}
public JComboBox createComboBox( TableModel model ) {
int count = model.getColumnCount();
Object[] items = new Object[count];
for( int i = 0 ;i < count;i++ ) {
String columName = model.getColumnName(i);
items[i] = new ColumnName( columName,i);
}
return new JComboBox(items);
}
JComboBox columnCombo = createComboBox( TabelaPessoal.getModel() );
private void Filtro(String query){
DefaultTableModel modelo = (DefaultTableModel) TabelaPessoal.getModel();
TableRowSorter<DefaultTableModel> pesquisa = new
TableRowSorter<DefaultTableModel>(modelo);
TabelaPessoal.setRowSorter(pesquisa);
ColumnName columnName = ( ColumnName ) columnCombo.getSelectedItem();
pesquisa.setRowFilter( RowFilter.regexFilter(query, columnName.getColumnIndex() ) );
}