tags:

views:

2157

answers:

4

Is there any way to do it?

+2  A: 

The best way would be to remove the corresponding element from the model.

Michael Borgwardt
But if I need to show him again later?
joycollector
Then you add it again :)
willcodejavaforfood
Finally I did this way... Two dataSets... One is full, the other one populates when fireDataTableChanged called... But I'm afraid it's slow...
joycollector
+2  A: 

Check out Sun's Tutorial for JTables and look at the Sorting and Filtering section.

willcodejavaforfood
I'm mistaken or filtering was enabled only in Java 1.6?
joycollector
Yes I'm afraid so.
willcodejavaforfood
JXTable from swinglabs if you want to try filtering in <1.6. You can also make your own TableModel that decorates another TableModel with sorting functions.
KitsuneYMG
A: 

You could create a wrapper around TableModel with methods like setVisible(int tableRow); when asked for rows, it would return only those rows that were visible.

Alex Feinman
Hmm... What method in TableModel asks for row? In table model we can only override getValueAt and getRowCount (and of course setValueAt)... I thought about it but found it impossible...
joycollector
getValueAt takes a row parameter...?
Alex Feinman
Yes of course, but even if you set all cells in this row to null it will be diaplayed as row with empty cells...
joycollector
Ah, but you don't return null for hidden rows; you skip over them when you count rows.E.g., if you hid row 2, and someone called getValueAt(2, 1), you would return row 3 data instead.
Alex Feinman
+1  A: 

There is the RowFilter<DefaultTableModel, Object> class you can use to filter out rows. The DefaultTableModel can be replaced by your own model. To filter, implement the method

@Override
public boolean include(Entry entry) {
// All rows are included if no filter is set
 if (filterText.isEmpty())
  return true;

 // If any of the column values contains the filter text,
 // the row can be shown
 for (int i = 0; i < entry.getValueCount(); i++)
 {
  String value = entry.getStringValue(i);
  if (value.toLowerCase().indexOf(filterText) != -1)
   return true;
 }

 return false;
}

When accessing rows, for instance listening to ListSelectionEvents, do not forget to translate the visible row index to the complete row index in your model. Java provides a function for this as well:

public void valueChanged(ListSelectionEvent e) 
{
  ListSelectionModel lsm = (ListSelectionModel)e.getSource();

  int visibleRowIndex = ... // Get the index of the selected row

  // Convert from the selection index based on the visible items to the
  // internal index for all elements.
  int internalRowIndex = tableTexts.convertRowIndexToModel(visibleRowIndex);

  ...
}
Thomas Feilkas
TY. But I was looking for a solution for Java 1.5...
joycollector