下面演示怎么动态过滤表格显示的内容
1 import javax.swing.*;
2 import javax.swing.table.*;
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.util.regex.*;
6
7 public class FilterTable {
8 public static void main(String args[]) {
9 Runnable runner = new Runnable() {
10 public void run() {
11 JFrame frame = new JFrame("Sorting JTable");
12 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13 Object rows[][] = {
14 { "Abc", "你", 1d },
15 { "AAB", "我", 2d },
16 { "ABC", "このページを印刷", 3.14 },
17 { "BBB", "hermit", 3.14 },
18 { "BBC", "0", 1.3 },
19 { "AAA", "!!!", 93.02 }
20 };
21 String columns[] = { "英文测试", "多语言测试", "数字测试" };
22 TableModel model = new DefaultTableModel(rows, columns) {
23 public Class getColumnClass(int column) {
24 Class returnValue;
25 if ((column >= 0) && (column < getColumnCount())) {
26 returnValue = getValueAt(0, column).getClass();
27 } else {
28 returnValue = Object.class;
29 }
30 return returnValue;
31 }
32 };
33 JTable table = new JTable(model);
34 final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(
35 model);
36 table.setRowSorter(sorter);
37 JScrollPane pane = new JScrollPane(table);
38 frame.add(pane, BorderLayout.CENTER);
39 JPanel panel = new JPanel(new BorderLayout());
40 JLabel label = new JLabel("Filter");
41 panel.add(label, BorderLayout.WEST);
42 final JTextField filterText = new JTextField();
43 filterText.addKeyListener(new KeyAdapter() {
44 public void keyReleased(KeyEvent e) {
45 String text = filterText.getText();
46 if (text.length() == 0) {
47 sorter.setRowFilter(null);
48 } else {
49 try {
50 sorter.setRowFilter(RowFilter
51 .regexFilter(text));
52 } catch (PatternSyntaxException pse) {
53 System.err.println("Bad regex pattern");
54 }
55 }
56 }
57 });
58
59 panel.add(filterText, BorderLayout.CENTER);
60 frame.add(panel, BorderLayout.NORTH);
61
62 frame.setSize(300, 250);
63 frame.setVisible(true);
64 }
65 };
66 EventQueue.invokeLater(runner);
67 }
68 }
69
效果不错吧,不过我还是喜欢swt多一点
posted on 2007-05-14 11:09
交口称赞 阅读(1304)
评论(3) 编辑 收藏 所属分类:
Java6