删除包含 ceratin 字母的字符串的 JTable 行

Remove JTable row with String containing ceratin letter

您好,我正在开发一个使用 JTable 连接单词的项目。在 table 中,连接在一起的单词之间有一个 @ 字符。

我基本上想删除 table 中包含字符 @ 的所有行。这是我到目前为止尝试过的:

for (int i = 0; i < table.getRowCount(); i++) {
                if ((boolean)table.getValueAt(i, 0).equals("\b[@]+\b")) {
                    table.remove(i);
                }
            }

此代码未按预期运行。我想知道编写这段代码的正确方法。感谢您提前回复。

您的代码调用 remove() method inherited from the Container class - you want to manipulate the table model used by your table. Assuming that you're using a DefaultTableModel, you can get the model from the table and use the removeRow() method.

此外,.equals("\b[@]+\b") 不检查包含“@”字符的字符串。它会检查您指定的文本是否完全匹配。您可能想看看 String.contains(...) 方法。

请记住,Swing JTable 中的数据是 stored in an underlying TableModel,而不是 JTable 对象本身。这样的东西应该可以工作。

    DefaultTableModel model = (DefaultTableModel) table.getModel();
    for (int i = 0; i < model.getRowCount(); i++) {
        if (model.getValueAt(i, 0) != null && model.getValueAt(i, 0).toString().contains("@")) {
            model.removeRow(i);
        }
    }