I have a JTable
with 7 columns and 2 rows. Below my JTable
I have a JTextField
. When I type something in JTextField
, I can easly get what I typed: String lookFor = this.jTextField2.getText();
But now, I would like to refresh my JTable
after I type something in my JTextField
but only when a row (or rows) contain(s) a text from JTextField
. I tried this, with no result:
public Object[][] getTableData(JTable table) {
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0; i < nRow; i++) {
for (int j = 0; j < nCol; j++) {
tableData[i][j] = dtm.getValueAt(i, j);
}
}
return tableData;
}
private void jTextField2KeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
DefaultTableModel newTableModel = new DefaultTableModel();
String lookFor = this.jTextField2.getText();
Object[][] td = getTableData(this.myTable);
int rows = td.length;
for (int i = 0; i < rows; i++) {
String brand = (String) td[0][0];
String model = (String) td[0][1];
String serialNumber = (String) td[0][2];
String date = (String) td[0][3];
String firstname = (String) td[0][4];
String lastname = (String) td[0][5];
String desc = (String) td[0][6];
if (brand.contains(lookFor) || model.contains(lookFor) || serialNumber.contains(lookFor) || date.contains(lookFor)
|| firstname.contains(lookFor) || lastname.contains(lookFor) || desc.contains(lookFor));
newTableModel.addRow(new Object[]{brand, model, serialNumber, date, firstname, lastname, desc});
}
this.myTable.setModel(newTableModel);
}