1

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);
    } 
4

2 回答 2

3

听起来你想做表格过滤。

阅读 Swing 教程中有关排序和过滤的部分,以获取一个工作示例,该示例将在您在文本字段中输入文本时过滤显示的行。

于 2013-10-16T20:51:00.090 回答
1

我尝试了您的代码,而您忘记做的是为新模型设置列。你必须要么

newTableModel.setColumnCount(7)

或者

newTableModel.setColumnIdentifiers(new String[] { ... });

只有当您这样做时,您才能在已显示的表格中看到新数据的样子。

于 2013-10-16T20:51:22.043 回答