gpt4 book ai didi

java - 过滤 JTable

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:47 24 4
gpt4 key购买 nike

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

}

}

关于java - 过滤 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29095906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com