我有一个JTable,想要过滤它。因此,我有一个文本字段,我从中获取输入:
eingabeF.addKeyListener(new KeyListener()
{
@Override
public void keyReleased(KeyEvent e) {
String eingabe = eingabeF.getText();
System.out.println(eingabe);
MovieUI.getTable().getSorter().setRowFilter(RowFilter.regexFilter(".*"+ eingabe +".*"));
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
});
但它不起作用。如何以正确的方式使用正则表达式过滤器?
谢谢!
-
使用
DocumentListener
(适用于所有JTextComponen
TS)而不是KeyListener
-
阅读 Oracle 教程如何使用表 - 排序和筛选有关
JTextField
、DocumentListener
和带RowFilter.regexFilter()
的工作代码示例
试试这个,这在我的项目中工作正常您可以将此搜索方法用于类中的每个 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;
}
}