this code below works for filtering JTable until I use english alphabet. It is also not case-sensitive. My goal is to filter white spaces and foreign characters. I need to replace characters in needle and in haystack somehow, for example č,ľ,ť,ž,ý,á replace with c,l,t,z,y,a. Does anybody have experience or working code for my request? Thanks in advance.
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Home extends javax.swing.JFrame {
DefaultTableModel model;
TableRowSorter sorter;
public Home() {
initComponents();
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
String data[] = {"šing","čamg","búng","wámg","fáng","raňk","moňk","púťk","šank","dung","puck","rig","an da da","ku nd ada","c ic inada"};
for(int i=0;i<data.length;i++) {
model.addRow(new Object[] {
data[i]
});
}
sorter = new TableRowSorter<TableModel>(model);
jTable1.setRowSorter(sorter);
}
private void initComponents() {///}
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String text = jTextField1.getText();
if(text.length() == 0) {
sorter.setRowFilter(null);
} else {
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
}
}
public static void main(String args[]) {///}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
You can use java.text.Normalizer
For example :
The first steps replace the character:
By its "decomposed form":
The second step delete all non ascii characters.
As @mKorbel pointed out:
KeyListener
(bad approach) but DocumentListener instead to listen for text field's text changes.Having said that, this is what I'd do:
Normalizer
, as already suggested, in order to attach a row filter to the table's row sorter that takes into account both the original entry text value and its normalized string representation.Example
Here's an MCVE to play with.
Apply the approach shown here in a custom
TableCellRenderer
, as discussed here.