Java by API/javax.swing.table/TableRowSorter
Версия от 17:43, 31 мая 2010; (обсуждение)
DefaultRowSorter: setRowFilter(RowFilter<? super TableModel, ? super Integer> filter)
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Main {
public static void main(String[] args) {
Object[][] data = { { "A", 5 }, { "B", 2 }, { "C", 4 }, { "D", 8 } };
String columnNames[] = { "Item", "Value" };
TableModel model = new DefaultTableModel(data, columnNames) {
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model);
RowFilter<Object, Object> filter = new RowFilter<Object, Object>() {
public boolean include(Entry entry) {
Integer population = (Integer) entry.getValue(1);
return population.intValue() > 3;
}
};
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
sorter.setRowFilter(filter);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Filtering Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
new TableRowSorter(TableModel model)
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
String[] columns = { "Item", "Price" };
Object[][] rows = { { "Potatoes", 10.98 }, { "Magazine", 7.99 },
{ "Can of soup", 0.89 }, { "DVD movie", 39.99 } };
TableModel model = new DefaultTableModel(rows, columns) {
public Class getColumnClass(int column) {
if (column >= 0 && column <= getColumnCount())
return getValueAt(0, column).getClass();
else
return Object.class;
}
};
JTable table = new JTable(model);
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
getContentPane().add(new JScrollPane(table));
setSize(200, 150);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}