过滤JTable

时间:2015-03-17 09:49:26

标签: java swing jtable tablerowsorter rowsorter

我正在做一个计算项目,需要我创建一个可以过滤的JTable。我已设法添加排序功能,但我无法添加过滤功能。我能找到的最接近的例子,就像我想要的那样,是能够启动它的TableFilterDemoProject和http://docs.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableFilterDemo的源代码

我正在尝试添加将代码过滤到此段代码的功能

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
//////////////////
import javax.swing.RowFilter;
import javax.swing.event.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.Dimension;
import java.awt.Component;
//////////////////


public class CompFrame
{

JFrame myMainWindow = new JFrame("This is my title");

JPanel  firstPanel = new JPanel(); //a panel for first tab

//first panel components
JScrollPane myScrollTable;


public void runGUI()
{
    myMainWindow.setBounds(10, 10, 1296, 756); //set position, then dimensions
    myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    myMainWindow.setLayout(new GridLayout(1,1));


    createFirstPanel(); //call method to create each panel

    myMainWindow.getContentPane().add(firstPanel); //adds the tabbedpane to mainWindow

    myMainWindow.setVisible(true); //make the GUI appear
}

public void createFirstPanel()
{
    firstPanel.setLayout(null);



    String[] aHeaders = {"Athlete ID","Forename","Surname"}; 
    String[][] sampleData = new String[3][3]; //rows,cols   
    sampleData[0][0] = "JS98";   
    sampleData[0][1] = "John";   
    sampleData[0][2] = "Smith";
    sampleData[1][0] = "DB56";   
    sampleData[1][1] = "David";   
    sampleData[1][2] = "Bower";
    sampleData[2][0] = "LL86";   
    sampleData[2][1] = "Lex";   
    sampleData[2][2] = "Luthor";





    JTable myTable = new JTable(sampleData,aHeaders);

    myTable.setAutoCreateRowSorter(true); //Sorts by a-z or 0-9 in the columns when a header is clicked

    myScrollTable = new JScrollPane(myTable); 
    myScrollTable.setSize(1282,600); 
    myScrollTable.setLocation(0,120); 
    System.out.println("Creating compare table");

    firstPanel.add(myScrollTable);
}

public static void main(String[] args)
{
    CompFrame cf = new CompFrame();
    cf.runGUI();
}
}

我将不胜感激任何帮助。感谢

1 个答案:

答案 0 :(得分:1)

它无论如何都不完美但如果你有一个可以应用动作事件的文本字段,你可以使用表格分类器。它不是最干净的,但它应该起作用

  public void searchTable(String input) {
         final TableRowSorter<TableModel> sorter = new TableRowSorter<>(yourTable.getModel());
         allEventsTable.setRowSorter(sorter);
         if (input.length() != 0) {
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + input));

         } else {
                sorter.setRowFilter(null);

         }

}