试试这个,这在我的项目中运行良好您可以对班级中的每个 JTable 使用此搜索方法,
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
search(myTable,myTextField);
}
public void search(JTable table, JTextField txtSearch) {
// I have used txtSearch1 in the RowColorRenderer class
this.txtSearch1 = txtSearch;
//Create new table sorter for the table
TableRowSorter sorter = new TableRowSorter(table.getModel());
//Add row filter to the tablerowsorter (regex)
sorter.setRowFilter(RowFilter.regexFilter("(?i).*\\Q" + txtSearch.getText() + "\\E.*"));
//Apply the results to the output table
table.setRowSorter(sorter);
if (table.getRowCount() == 0) {
//Display message like nothing found
}
for (int i = 0; i < table.getColumnCount(); i++) {
RowColorRenderer rowRenderer = new RowColorRenderer(i);
TableColumn column = table.getColumnModel().getColumn(i);
column.setCellRenderer((TableCellRenderer) rowRenderer);
}
}
这是单元格渲染器,用于更改从搜索 JTextField 中找到文本的单元格的颜色
public class RowColorRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private int colNo = 0;
RowColorRenderer(int col) {
colNo = col;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
JComponent jc = (JComponent) comp;
if (!isSelected) {
if (table.getValueAt(row, colNo) != null) {
String str = table.getValueAt(row, colNo).toString();
if (!str.isEmpty()) {
if (Pattern.compile("(?i).*\\Q" + txtSearch1.getText() + "\\E.*").matcher(str).find()) {
if (!txtSearch1.getText().equals("")) {
// setBackground(Color.LIGHT_GRAY);
// setFont(new Font("Serif", Font.BOLD, 18));
// setHorizontalAlignment(CENTER);
setForeground(Color.blue);
} else {
setBackground(table.getBackground());
setForeground(table.getForeground());
// setHorizontalAlignment(CENTER);
}
} else {
setBackground(table.getBackground());
setForeground(table.getForeground());
}
}
}
}
return this;
}
}