Jtable的排序、过滤功能

排序

TableRowSorter<MyTableModel> tableRowSorter = new TableRowSorter<MyTableModel>(myTableModel);
jtable.setRowSorter(tableRowSorter);//点击表格列头进行排序,(jdk6开始支持)      

 过滤

package test.tool.gui.dbtool.dialog;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import test.tool.gui.dbtool.frame.DBOperation;
import test.tool.gui.dbtool.mycomponent.MyJTextField;

public class FilterDialog extends javax.swing.JDialog {

	private static final long serialVersionUID = 1L;
	private MyJTextField jTextField_search;
	DBOperation mainFrame = null;
    
	private static FilterDialog instance = null;
	public static FilterDialog getInstance(DBOperation parent, boolean modal){
		if(instance == null){
			instance = new FilterDialog(parent,modal);
		}
		return instance;
	}
	
    public FilterDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        mainFrame = (DBOperation)parent;
        this.setLocationRelativeTo(parent);
        initComponents();
    }

    private void initComponents() {

        jTextField_search = new MyJTextField();
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().add(jTextField_search, java.awt.BorderLayout.CENTER);//东西南北中布局
        getContentPane().add(jTextField_search);
        setTitle("过滤条件");
        pack();
        setSize(200, 80);
        
        jTextField_search.addKeyListener(new KeyAdapter(){
			public void keyReleased(KeyEvent e) {		
				JTable jtable = mainFrame.getCurrentJtable();
				if(jtable != null){			
					String text = jTextField_search.getText();	
					if(text==null || text.length()==0){
						((TableRowSorter<TableModel>)jtable.getRowSorter()).setRowFilter(null);
					}else{
						if(jtable.getRowSorter()!=null){//当Jtable中无数据时,jtable.getRowSorter()是null。				
							((TableRowSorter<TableModel>)jtable.getRowSorter()).setRowFilter(RowFilter.regexFilter(text));
						}
					}
				}	
			}
        });
    }
}

 

 

效果:


Jtable的排序、过滤功能
 

 

你可能感兴趣的:(jtable)