javaswingjtableswingutilities

Make JTable cells perfectly square


Is there any mechanism to make a JTable's cells perfectly square? Currently I'm just overriding this method in the table's implementation:

@Override
public int getRowHeight() {
    return this.getColumnModel().getColumn(0).getWidth();
}

This works in most cases like in the image below where I have a 15x15 JTable:

enter image description here

But if I extend the JPanel the table sits on width wise the cell's continue to expand width and length wise resulting in the lower 3 rows being cut off:

enter image description here

I am wondering if there is a better solution to have a JTable's cells be perfectly square?


Solution

  • Further on my comment, you would need to use some logic to work out if the width or height is smaller (The limiting factor). Then based on which is smaller you can change the size of the cells.

    Rather than using an override on the row height and trying to mess with column overrides, I instead reccomend intercepting the JTable componentResized event and simply set the sizes we want. I have assumed a fixed number of cells (15x15) for this example:

    int rowCount = 15;
    int colCount = 15;
    
    your_JTable.addComponentListener(new ComponentAdapter(){
    
        @Override
        public void componentResized(ComponentEvent e){
            //Get new JTable component size
            Dimension size = getSize();
            
            int cellSize;
    
            //Check if height or width is the limiting factor and set cell size accordingly
            if (size.height / rowCount > size.width / colCount){
                cellSize = size.width / colCount;
            }
            else{
                cellSize = size.height / rowCount;
            }
            
            //Set new row height to our new size
            setRowHeight(cellSize);
            
            //Set new column width to our new size
            for (int i = 0; i < getColumnCount(); i++){
                getColumnModel().getColumn(i).setMaxWidth(cellSize);
            }
        }
    });
    

    This provides perfectly square cells in JDK13 when resized both horizontally or vertically or both. I realise that I answered your previous question as well, so here is a working example using that code:

    enter image description here