2013-04-10 83 views
0

我有一個Java表和TableModel.each row(element)有一個ID。我想顯示特定的ID。如何過濾這些元素?選定的ID可以更改。在java中顯示特定行JTable

例如:

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"); 

我想顯示與此ID的元件,例如{1 39 45 55 22}。

如何篩選這些ID?

+1

http://stackoverflow.com/questions/1107911/how- can-i-filter-rows-in-a-jtable – jalopaba 2013-04-10 15:31:58

+0

你確定你使用Class [] columnClasses = {Integer.class,String.Class}來覆蓋getColumnClass,以便更快地發佈[SSCCE](http ://sscce.org/),可短時間編譯 – mKorbel 2013-04-10 16:16:05

回答

3

你可以用的RowFilter和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); 

測試,它爲我工作

希望這有助於

+0

+1 RowFilter – mKorbel 2013-04-10 16:19:21

+0

謝謝Harlandraka 我更改了代碼。我該怎麼做? – Nasir 2013-04-12 03:45:11

+0

@nasir您要求通過ID過濾您的行,所以無論您添加到類中的字段有多少,此代碼都將正常工作 – BackSlash 2013-04-12 07:27:22