TableModelmodel=newDefaultTableModel(rows,columns); JTabletable=newJTable(model); RowSortersorter=newTableRowSorter(model); table.setRowSorter(sorter); |
importjavax.swing.*; importjavax.swing.table.*; importjava.awt.*; publicclassTestSortedTable { publicstaticvoidmain(Stringargs[]) { JFrameframe=newJFrame("JTable的排序测试"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //表格中显示的数据 Objectrows[][]= { {"王明","中国",44}, {"姚明","中国",25}, {"赵子龙","西蜀",1234}, {"曹操","北魏",2112}, {"BillGates","美国",45}, {"Mike","英国",33}}; Stringcolumns[]= {"姓名","国籍","年龄"}; TableModelmodel=newDefaultTableModel(rows,columns); JTabletable=newJTable(model); RowSorter<TableModel>sorter=newTableRowSorter<TableModel>(model); table.setRowSorter(sorter); JScrollPanepane=newJScrollPane(table); frame.add(pane,BorderLayout.CENTER); frame.setSize(300,150); frame.setVisible(true); } } |
TableModelmodel=newDefaultTableModel(rows,columns) { publicClassgetColumnClass(intcolumn) { ClassreturnValue; if((column>=0)&&(column<getColumnCount())) { returnValue=getValueAt(0,column).getClass(); } else { returnValue=Object.class; } returnreturnValue; } }; |
button.addActionListener(newActionListener() { publicvoidactionPerformed(ActionEvente) { Stringtext=filterText.getText(); if(text.length()==0) { sorter.setRowFilter(null); } else { sorter.setRowFilter(RowFilter.regexFilter(text)); } } }); |
importjavax.swing.*; importjavax.swing.table.*; importjava.awt.*; importjava.awt.event.*; publicclassTestFilter { publicstaticvoidmain(Stringargs[]) { JFrameframe=newJFrame("JTable的过滤测试"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Objectrows[][]= { {"王明","中国",44}, {"姚明","中国",25}, {"赵子龙","西蜀",1234}, {"曹操","北魏",2112}, {"BillGates","美国",45}, {"Mike","英国",33}}; Stringcolumns[]= {"姓名","国籍","年龄"}; TableModelmodel=newDefaultTableModel(rows,columns) { publicClassgetColumnClass(intcolumn) { ClassreturnValue; if((column>=0)&&(column<getColumnCount())) { returnValue=getValueAt(0,column).getClass(); } else { returnValue=Object.class; } returnreturnValue; } }; finalJTabletable=newJTable(model); finalTableRowSorter<TableModel>sorter=newTableRowSorter<TableModel>(model); table.setRowSorter(sorter); JScrollPanepane=newJScrollPane(table); frame.add(pane,BorderLayout.CENTER); JPanelpanel=newJPanel(newBorderLayout()); JLabellabel=newJLabel("过滤"); panel.add(label,BorderLayout.WEST); finalJTextFieldfilterText=newJTextField(""); panel.add(filterText,BorderLayout.CENTER); frame.add(panel,BorderLayout.NORTH); JButtonbutton=newJButton("过滤"); button.addActionListener(newActionListener() { publicvoidactionPerformed(ActionEvente) { Stringtext=filterText.getText(); if(text.length()==0) { sorter.setRowFilter(null); } else { sorter.setRowFilter(RowFilter.regexFilter(text)); } } }); frame.add(button,BorderLayout.SOUTH); frame.setSize(300,250); frame.setVisible(true); } } |