I need to assign a fixed width to a few columns of a JTable
and then an equal width to all the other columns.
Suppose a JTable
has 5 columns. The first column should have a width of 100 and the second one a width of 150. If the remaining width of the JTable
is 600 after setting the width of the two columns, I'd like to evenly split it among the other three columns.
The problem is table.getParent().getSize().width
is often 0, even if it is added to the JFrame
and visible, so I can't use it as a basis.
How do I go about doing this?
I think you need to use
table.getPreferredSize()
instead. Try this code snippet:As you'll see,
Name
column will have a width of 100,Category
will have a width of 150,Color
column will fit at 70% of remanent width andRanking
will fit at last 30%.Update
Based on this comment:
Solution could be play with
setMinWidth
andsetMaxWidth
methods to fix static columns width, or you can implement your own TableColumnModelListener. In the example above replacesetPreferredWith
lines as follows and try set frame's preferred size as you wish:I had to dynamically set my table columns width for a project that had to display correctly on different screen resolution DPI settings. The idea for my solution came from dic19s answer.
Basically I got the preferred size of the JPanel where the JSrollPane of the JTable was placed and work great. Please see below
Hope this helps somebody
Thanks
Let the table's resize mode do the work for you. Set the resize mode to all columns and set the min/max values of the fixed columns:
It think it would be easier to use (and re-use) relative component resizing if we encapsulate it in an own class. Since I also was confronted with the same issue, I would like to post my code here.
From a client perspective I would like to do something like this
So I first defined the
ComponentResize
interface and implement aTableColumnResize
The
ComponentResize
interface decouples the way a component's size is set from the concrete APIs. E.g. aTableColumn
's width can be set viasetPreferredWidth(int)
while aJComponent
's size can be set bysetPreferredWidth(Dimension)
Than I implemented the
RelativeWidthResizer
that encapsulates the relative width calculation logic.