0

I am trying to set the size of a table in Java.

    pTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    pTable.getColumnModel().getColumn(0).setPreferredWidth(120);
    pTable.getColumnModel().getColumn(1).setPreferredWidth(100);

The table is in the correct position in my frame but there is this unnecessary blank space to the right of the last column. This is what I get:

enter image description here

I would just like to eliminate that blank white space that is to the right of the first name column.

Please don't lock this question, there is a similar one out there but it did not have any info that was of any help to me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hax
  • 81
  • 1
  • 7
  • Don't set the size of the columns? Maybe try using `AUTO_RESIZE_LAST_COLUMN` instead of `AUTO_RESIZE_OFF` – MadProgrammer Dec 04 '17 at 21:27
  • I want them to be size because if they aren't they fill up that entire white space and that is much wider than I want my table to be. AUTO_RESIZE_LAST_COLUMN makes the columns not change sizes at all – hax Dec 04 '17 at 21:35
  • Okay, so which of these two situations is less desirable to you, the white space or the column filling the remaining space? – MadProgrammer Dec 04 '17 at 21:37
  • Both are undesirable, I just want my table to be less wide and not show this remaining white space. If I had the last column fill the white space it defeats the purpose since I wanted my table to be less wide originally. – hax Dec 04 '17 at 21:42
  • 1
    Then consider using a different layout manager - You should consider having a look [this example](https://stackoverflow.com/questions/37341354/resize-jtable-to-fit-number-of-rows) which will effect the `preferredScrollableViewportSize`, see the up-voted answer and not the accepted answer – MadProgrammer Dec 04 '17 at 21:42
  • Without sizing the columns, the columns fill the white space proportionately, so all I want to do is make the table less wide without creating that white space – hax Dec 04 '17 at 21:43

1 Answers1

0

A JTable has a predefined preferred size.

You can reset this by doing something like:

JTable table = new JTable(5, 2);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(120);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.setPreferredScrollableViewportSize(table.getPreferredSize());

Now the width will be the width of the columns, but of course the height will be the height of all the rows as well.

But if you add the scrollpane to the frame using BorderLayout.LINE_START as the constraint, then the width of the table will be preserved and the height will vary with the height of the frame.

camickr
  • 321,443
  • 19
  • 166
  • 288