Correctly sizing the header for one column of a JTable
Asked Answered
S

1

2

I have a table with 3 columns and want the first one to be the minimum size needed. The header is "Level" and seems to be 25-29 pixels depending on the font/OS I use. However the table header seems to require at least 35 on Windows and 52 on Mac to display it without ellipses. I can't figure out why the extra space is needed (there's no border, etc).

I finally found that the following will give the required size on Windows (35) but on Mac it returns 36 which is not enough (most likely due to the sort arrow indicator being next to, rather than above, the text)...

table.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(null, table.getColumnModel().getColumn(0).getHeaderValue(), false, false, 0, 0).getPreferredSize().width

What's the right way to do this that's platform independent? Or, is there a way on Mac to calculate the extra space needed so that I don't have to hardcode something like adding 15 or so pixels to the above result?

Softfinned answered 12/9, 2011 at 17:40 Comment(0)
F
1

I'd stick with setPreferredScrollableViewportSize() and the approach suggested in Setting and Changing Column Widths, followed by pack().

Fefeal answered 12/9, 2011 at 18:30 Comment(5)
with another examples #7259443 +1Bushman
@mKorbel: Thanks! Good link. I'd forgotten about Table Column Adjuster.Fefeal
Ok, the line I use above was based on the example at Setting and Changing Column Widths which works on Windows but not on Mac. Table Column Adjuster doesn't just use the default renderer and adding that part gets this working on Mac too. Thanks!Softfinned
Ah, the example fails on Mac OS, which uses AquaTableHeaderUI. Kudos to mKorbel for the reminder and @camickr for the solution! See also this Q&A.Fefeal
the tutorial example is ... ehem .. suboptimal a) misses per-column renderers b) let's the model decide about "longest" value - which it can't as it doesn't know how it will be rendered. +1 to @camickr for catching the margin :-)Fries

© 2022 - 2024 — McMap. All rights reserved.