Question

How to center JTable cells to the middle of the JTable?

I am using table to paint boxes in the table, but when resized, the cells remain left-top aligned. When the table fits the cells nicely, it is not a problem. But when I resize the window (and the table with it), it is wrong:

fine lookingwrong

My question is, is it possible to make the cells appear in the middle of the table? I suppose I could use glues on sides (this is BorderLayout), but I would rather take this approach.

Was it helpful?

Solution

Since your TableCellRenderer is just painting colored blocks, you could put the table in a FlowLayout and override getPreferredScrollableViewportSize().

private static final int WIDE = 10;
private static final int HIGH = 20;
private static final int SIZE = 50;
...
@Override
public Dimension getPreferredScrollableViewportSize() {
    return new Dimension(WIDE * SIZE, HIGH * SIZE);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top