简体   繁体   中英

Adding a row to JTable

I'm trying tobuild a file browser using JTable for filename, size, etc. But swing crash when i try add a row in JTable. Can someone tell me, what i'm doing wrong?

Thanks.

Source code

What is wrong?
I suspect the TableModel has no columns - columns where added to the ColumnModel of the table but not to the TableModel . At least set its column count to 4.

I also strongly suggest creating the model ( DefaultTableModel ) before creating the table, so it can be used to create the table - no need to add columns to table. Even better use an own model, extending AbstractTableModel - gives better control (mostly for non trivial cases).


Example (minimal) for own model:

class FileInfoModel extends AbstractTableModel {
    private final String[] columns = {"", "Name", "Size", "Date"};

    private final List<FileInfo> data = new ArrayList<>();

    @Override
    public int getColumnCount() {
        return columns.length;
    }        

    @Override
    public String getColumnName(int col) {
        return columns[col];
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public Object getValueAt(int row, int col) {
        FileInfo info = data.get(row);
        switch (col) {
            case 0: return info.getFileType();
            case 1: return info.getFileName();
            case 2: return info.getFileSize();
            case 3: return info.getLastModified();
            default: throw new IllegalArgumentException("col: " + col);
        }
    }

    public void addInfo(FileInfo info) {
        if (data.add(info)) {
            var row = data.size() - 1;
            fireTableRowsInserted(row, row);
        }
    }
}

no need for an extended table, just new JTable(model) using above model instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM