Nikhil Kadam
Nikhil Kadam

Reputation: 159

How to add column with values in JTable?

I am new to Swing. I have JTable with columns. I want to add a new column to the existing table with values in it. I am able to add a new column in table using model.addColumn("test"). But it gives me blank column - rather I want to display values in column and add it in the table.

Upvotes: 0

Views: 1674

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

Use DefaultTableModel#addColumn(Object, Object[]

Adds a column to the model. The new column will have the identifier columnName. columnData is the optional array of data for the column. If it is null the column is filled with null values. Otherwise, the new data will be added to model starting with the first element going to row 0, etc. This method will send a tableChanged notification message to all the listeners.

Upvotes: 1

//I make new model

    private void setNewTableModel(){

        String[] header = new String[nArrays + 1];
        header[0] = "";
        for (int i = 1; i < header.length; i++)
            header[i] = "Array" + i;
        Object[][] data = new Object[4][nArrays + 1];
        for (int i = 0; i < data.length; i++) 
            for (int j = 1; j < header.length; j++){
            data[i][0] = "\"" + (i + 2) + "\"";
            data[i][j]=j+i;
        }
        table.setModel(new DefaultTableModel(data, header));
    }

Upvotes: 0

Related Questions