我有一个填充了数据的表。我有一个comboBox,用户应该可以选择其中一个选项,点击过滤按钮,表格会显示过滤后的结果。我试图使用tableRowSorter.setRowFilter方法,但似乎无法弄清楚它是如何工作的。有人会介意解释该方法是如何工作的,还是有任何toher建议?感谢
答案 0 :(得分:0)
详细了解Sorting and Filtering in JTable
。
以下是RowFilter
的简单示例,请检查:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class Example extends JFrame {
private JTable table;
private DefaultTableModel model;
private TableRowSorter<DefaultTableModel> sorter;
public Example() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
pack();
setVisible(true);
}
public static void main(String... strings) {
new Example();
}
private void initComponents() {
JPanel p = new JPanel();
final JComboBox<String> box = new JComboBox<>(new String[]{"","1","2","3"});
JButton b = new JButton("filter");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(box.getSelectedItem().toString(), 0);
sorter.setRowFilter(rf);
}
});
p.add(box);
p.add(b);
table = new JTable(model = new DefaultTableModel(3,3));
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
add(p,BorderLayout.SOUTH);
add(new JScrollPane(table));
}
}