Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge cell in DefaultTableModel/JTable?

I searched a lot and got some answers for this Q. but many of them referred to links which give 404 error. I want to make table like this:

No. of cells to be merged is not fixed

Is there any method in java for this?

like image 883
Nikhil Chilwant Avatar asked Feb 18 '14 14:02

Nikhil Chilwant


2 Answers

MultiSpanCellTableExample demonstrates how to merge cells by creating a custom TableUI. There seem to be a problem in this example that causes StackOverflowError, at least in Java 6. To fix this, inside AttributiveCellTableModel.setDataVector() replace:

setColumnIdentifiers(columnNames);

with:

this.columnIdentifiers = columnNames;

IE:

public void setDataVector(Vector newData, Vector columnNames) {
    if (newData == null)
        throw new IllegalArgumentException(
                "setDataVector() - Null parameter");
    dataVector = new Vector(0);
    // setColumnIdentifiers(columnNames);
    this.columnIdentifiers = columnNames;
    dataVector = newData;

    cellAtt = new DefaultCellAttribute(dataVector.size(),
            columnIdentifiers.size());

    newRowsAdded(new TableModelEvent(this, 0, getRowCount() - 1,
            TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
}

The problem is that setColumnIdentifiers calls into setDataVector hence triggering the StackOverflowError. Once fixed, this is how the example looks like:

enter image description here

There is also a ready solution from JIDE, unfortunately it is not free. Here is for example CellSpanTable:

enter image description here

like image 151
tenorsax Avatar answered Oct 05 '22 17:10

tenorsax


MultiCellSpanTableExample is fine, but it has a little problem that can become a huge problem if your table has too many columns. As you can see in the example given by tenorsax, apparently each table column has an extra pixel in their width. Those additional pixels add up, making each column more displaced than the last.

I could simply fix that by replacing the line:

cellFrame.width = aColumn.getWidth() + columnMargin;

with:

cellFrame.width = aColumn.getWidth() + columnMargin - 1;

I know nobody asked, but I hope this helps someone. :)

like image 25
Pedro Lima Avatar answered Oct 05 '22 19:10

Pedro Lima