在添加新行之前验证行不为空

Verifying row is not empty before adding new row

我正在开发一个工具,可以将内容从 JTable 保存到 CSV 文件,我有这个 "add row" 按钮来添加新行,但我需要最后一个要在每个单元格上填充的行,然后允许添加新行。

这是我的代码,但这不会创建新行,也不会在控制台上引发任何错误。

 private void btnAddRowActionPerformed(java.awt.event.ActionEvent evt) { 
    for(int i=0;i<=jTable1.getColumnCount();i++){
        if(jTable1.isRowSelected(jTable1.getRowCount())){
           do{
              model.insertRow(jTable1.getRowCount(), new Object[]{});
           } while(jTable1.getValueAt(jTable1.getRowCount(), i).equals(""));
        }
    }
}

好的,您的意思似乎是,在最后一行完全完成之前,不应允许用户添加新行...

你现有的循环没有意义,基本上,对于每一列,你正在检查是否选择了最后一行,并为每一列空白插入一个新行 ("") ...?

请记住,通常 Java 是零索引,这意味着最后一行实际上是 jTable1.getRowCount() - 1,因此,您的 if isRowSelected 不太可能是真的,这实际上是好东西,否则你会一团糟...

假设我正确理解你的问题(因为它有点含糊),你可以尝试更多类似的东西...

boolean rowCompleted = true;
int lastRow = jTable1.getRowCount() - 1;
if (jTable1.isRowSelected(lastRow)) {
    for (int col = 0; col < jTable1.getColumnCount(); col++) {
        Object value = jTable.getValueAt(lastRow, col);
        if (value == null || value.toString().trim().isEmpty()) {
            rowCompleted = false;
            break;
        }
    } 
}

if (rowCompleted) {
    // Insert new row...
} else {
    // Show error message
}

也许使用 TableModelListener

每次在 table 的最后一行更新单元格时,您都会检查以确保所有列都有数据。如果所有列都有数据,则启用 "Add Row" 按钮,否则禁用该按钮。

我正在检查这个 post 并且我使用了由 MadProgrammer post 编辑的代码,但我做了一些修改并根据您的需要使它正常工作。如果需要可以找我要项目,我很乐意提供给你

private void btnAddRowActionPerformed(java.awt.event.ActionEvent evt) {                                          
    boolean rowCompleted;
    int lastRow = jTable1.getRowCount()-1;
    if(jTable1.isRowSelected(lastRow)){
        for(int col=0;col<jTable1.getColumnCount();col++){
            Object value = jTable1.getValueAt(lastRow, col);
            if(value == null || value.toString().trim().isEmpty()){
                rowCompleted=false;
            }
            else{
                rowCompleted=true;
            }
            if(rowCompleted==true){
                model.insertRow(jTable1.getRowCount(), new Object[]{});
            }
            else{
                JOptionPane.showMessageDialog(null, "Something went worng. Try this:\n - Please select a row before adding new row.\n - Please verify there are no empty cells","Processing table's data",1);
            }
            break;
        }
    }
    else{
        JOptionPane.showMessageDialog(null, "Something went wrong. Verify this:\n - There is not any row selected.\n - You can only create new rows after last row","Processing table's data",1);
    }

} 

希望这对您有所帮助,但首先要感谢 MadProgrammer :D