Filtering a JTable



我正在做一个计算项目,该项目要求我创建一个可以过滤的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();
}
}

如果有任何帮助,我将不胜感激。感谢

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

  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);
         }
}

相关内容

  • 没有找到相关文章

最新更新