Pregunta

I have a Java Table and TableModel.each row(element) has a ID. I want to show specific IDs . How can filter this elements? Selected IDs can be changed.

For example:

public class L {
int id;
String name;
String family;
}

//----

private static final String[] columnNames = { "name","family"};
private static final Class[] columnClasses = {class.String.class,String.Class};
private Vector<L> list = Vector<L>();

list.add(new L(1,"A","b"));
.
.
.
list.add(new L(100,"AB","aa");

I want to show elements with this IDs, for example {1 39 45 55 22}.

How can filter these IDs?

¿Fue útil?

Solución

You can do it with RowFilter and TableRowSorter:

final int[] ids = new int[]{1, 39, 45, 55, 22};
RowFilter<Object, Object> filter = new RowFilter<Object, Object>() {
  public boolean include(Entry entry) {
    L currentObject = (L) (entry.getValue(0));
    for(int i=0;i<ids.length;i++){
        if(currentObject.getId()==ids[i]){
            return true;
        }
    }
    return false;
  }
};

TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
sorter.setRowFilter(filter);
yourTable.setRowSorter(sorter);

Tested, it works for me

Hope this helps

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top