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?

Sean Dawson
  • 232
  • 3
  • 13

1 Answers1

1

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

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    with another examples http://stackoverflow.com/questions/7258943/how-do-i-get-a-jtable-header-to-display-entire-column-names-instead-of-shortening +1 – mKorbel Sep 12 '11 at 18:39
  • @mKorbel: Thanks! Good link. I'd forgotten about `Table Column Adjuster`. – trashgod Sep 12 '11 at 18:42
  • 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! – Sean Dawson Sep 12 '11 at 19:40
  • Ah, the [example](http://download.oracle.com/javase/tutorial/uiswing/examples/components/TableRenderDemoProject/src/components/TableRenderDemo.java) fails on Mac OS, which uses `AquaTableHeaderUI`. Kudos to mKorbel for the reminder and @camickr for the solution! See also this [Q&A](http://stackoverflow.com/questions/7137786/how-can-i-put-a-control-in-the-jtableheader-of-a-jtable). – trashgod Sep 12 '11 at 20:12
  • 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 :-) – kleopatra Sep 13 '11 at 09:42