Reputation: 7724
I am doing a computing project which requires me to create a JTable which one could filter through. I have managed to add a sort function but I am unable to add a filter function. The closest example I could find, which is similar to what I am wanting, is the TableFilterDemoProject with the ability to launch it and the source code at http://docs.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableFilterDemo
I am trying to add the ability to filter my code to this piece of code
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();
}
}
I would appreciate any help. Thanks
Upvotes: 1
Views: 1619
Reputation: 612
It's not perfect by any means but provided you have a textfield that you can apply an action event to, you can use a table sorter. It's not the cleanest but it should work
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);
}
}
Upvotes: 1